View Full Version : PHP within Required field(s) validation

04-11-2011, 09:23 PM
1) Script Title: Required field(s) validation

2) Script URL (on DD): http://www.dynamicdrive.com/dynamicindex16/requiredcheck.htm

3) Describe problem: I want to run this validation on one of my registration sites. The problem comes up because the Form is generated through PHP. So when I click to register on a product the field name is made up by combining field ID and product ID. So the Field name could be "Players_name11" for one form and then "Players_name14" for another product.

In my case the Field ID will ways stay the same, it's the product ID that will change for each form. So is there a way to pull that product ID into the var fieldRequired = Array("First_name"); portion of the script? So that it would automatically add in the product ID of the current product.

Hopefully it's possible and someone can help. Thank you very much for your time.


04-12-2011, 06:30 PM
Well, the required field names portion of the function can be made dynamic:

var fieldRequired = Array("FirstName", "LastName");

Instead of the above, you can modify the function to accept these fields as a parameter of the function, enabling you to pass in a different array of required field names. The below is the original script, but changed to do this (new parts in red):

<script language="JavaScript">

* Required field(s) validation v1.10- By NavSurf
* Visit Nav Surf at http://navsurf.com
* Visit http://www.dynamicdrive.com/ for full source code

function formCheck(formobj, requiredfields){
// Enter name of mandatory fields
var fieldRequired = requiredfields;
// Enter field description to appear in the dialog box
var fieldDescription = Array("First Name", "Last Name");
// dialog message
var alertMsg = "Please complete the following fields:\n";

var l_Msg = alertMsg.length;

for (var i = 0; i < fieldRequired.length; i++){
var obj = formobj.elements[fieldRequired[i]];
if (obj){
case "select-one":
if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == ""){
alertMsg += " - " + fieldDescription[i] + "\n";
case "select-multiple":
if (obj.selectedIndex == -1){
alertMsg += " - " + fieldDescription[i] + "\n";
case "text":
case "textarea":
if (obj.value == "" || obj.value == null){
alertMsg += " - " + fieldDescription[i] + "\n";
if (obj.type == undefined){
var blnchecked = false;
for (var j = 0; j < obj.length; j++){
if (obj[j].checked){
blnchecked = true;
if (!blnchecked){
alertMsg += " - " + fieldDescription[i] + "\n";

if (alertMsg.length == l_Msg){
return true;
return false;
// -->

<!--SAMPLE FORM -------------------------------->
<form name="formcheck" onsubmit="return formCheck(this, ['FirstName', 'LastName']);">
First Name: <input type=text name="FirstName" size="25"><br>
Last Name: <input type=text name="LastName" size="25"><br>
<input type=submit value="Submit Form">

That's the basic idea to implementing what you're asking anyway.