This is my first time really using HTML, Javascript and PHP.
This is part of a prototype for a project for my SW Eng. course.
The problem I am having is that the form is not going through the validation. The user is supposed to be able to search by either last name or SSN, so I have a 2 radio buttons corresponding to the 2 search fields, and based on the choice, the function will validate the chosen input. The problem is when I test the page, none of the alerts pop up, making me conclude that the function isn't even being executed, however the data is being passed to the php page.

<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
		<title>MVC Student Information System - Search</title>
		<script type="text/javascript">
function validate(form){
				if (form.radChoice.value == "S"){
					alert("Branch 1 has executed");
					var strSSN = String(form.SSN.value);
					if (/\b\d{9}\b/.test(strSSN) == false){
						alert("SSN must contain exactly 9 digits");
						return false;
					}
					else{
						return true;
					}
				}
				else if (form.radChoice.value == "N"){
					alert("Branch 2 has executed");
					if (lName.value == NULL || lName.value == ""){
						alert("Name cannot be blank.");
						return false;
					}
					else{
						return true;
					}
				}
				else{
					alert("This should not be happening");
					return false;
				}
			}
</script>
	</head>
	<body>
        <h1>MCV Student Information System</h1>
		<h2>Welcome to the Administrative Add Student Page</h2>
		<h4>Please select a search parameter and click the search button</h4>
		<form action="adminSearch.php" name="search" method="post" 
			onsubmit="return validate(this);">
			<input type="radio" name="radChoice" value="S" />SSN:      <input type="text" name="SSN" /><br>
			<input type="radio" name="radChoice" value="N" />Last Name:<input type="text" name="lName" /><br>
			<input type="submit" name="btnSearch" value="Search" />
		</form>
		<h3><a href="adminMenu.html">Back to Administrative Menu</a></h3>
	</body>
</html>

Unfortunately, you have to loop to pick up the checked value from a radio group. AFAIK, there's no convenient method as for select menus.

Try this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>MVC Student Information System - Search</title>
<script type="text/javascript">
function validate(form){
  var val = null;
  for(var i=0; i<form.radChoice.length; i++ ){//loop through radio group to find which one is checked
    if(form.radChoice[i].checked){
		val = form.radChoice[i].value;
		break;//break out of the loop
	}
  }
  switch(val){
    case 'S':
      var strSSN = form.SSN.value;
      if (/\b\d{9}\b/.test(strSSN) == false) {
        alert("SSN must contain exactly 9 digits");
        return false;
      }
      else { alert('S - OK'); return false; }//debug statement
      break;
	case 'N':
      var lName = form.lName.value;
      if (!lName) {
        alert("Name cannot be blank.");
        return false;
      }
      else { alert('N - OK'); return false; }//debug statement
      break;
	  default:
        alert("No radio button checked");
		return false;
  }
  //further form validation tests here ...
  return true;
}
</script>
</head>
<body>

<h1>MCV Student Information System</h1>
<h2>Welcome to the Administrative Add Student Page</h2>
<h4>Please select a search parameter and click the search button</h4>

<form action="adminSearch.php" name="search" method="post" onsubmit="return validate(this);">
<input type="radio" id="radChoice_1" name="radChoice" value="S" /><label for="radChoice_1">SSN:</label> <input type="text" name="SSN" /><br>
<input type="radio" id="radChoice_2" name="radChoice" value="N" /><label for="radChoice_2">Last Name:</label> <input type="text" name="lName" /><br>
<input type="submit" name="btnSearch" value="Search" />
</form>

<h3><a href="adminMenu.html">Back to Administrative Menu</a></h3>

</body>
</html>

Tested in IE6.
Notes:

  • Converted if/else if/else to a switch/case structure which I find neater.
  • In a validator of this type, it's wrong to return true on a single success because there might be further validation checks further down the function which will fail. Hence in the code above, failures cause immediate return false , while successes do nothing until return true right at the bottom (form has passed all the traps).
  • A few other tweaks.

Hope this helps.

Airshow

when you have more than one form element with the same name (in your case you have two radio buttons named radChoice) you then need to treat it as an array.

So in your case, on what you posted instead of:

if (form.radChoice.value == "S"){...}

you needed:

if (form.radChoice[0].value == "S"){...}

similarly, the other check should have been:

else if (form.radChoice[1].value == "N"){...}
if (form.radChoice[0].value == "S"){...}
else if (form.radChoice[1].value == "N"){...}

Absolutely no good I'm afraid - reason being form.radChoice[0].value is guaranteed to be "S" and form.radChoice[1].value is guaranteed to be "N".

There's no point testing the values - they don't change.

Test the .checked property in a loop as per my code above.

Airshow

Absolutely no good I'm afraid

Yes of course. Major oversight on my part. Good catch Airshow.
As pointed out, it should have been:

if (form.radChoice[0].checked ){...}
      else if (form.radChoice[1].checked ){...}

This is my first time really using HTML, Javascript and PHP.
This is part of a prototype for a project for my SW Eng. course.
The problem I am having is that the form is not going through the validation. The user is supposed to be able to search by either last name or SSN, so I have a 2 radio buttons corresponding to the 2 search fields, and based on the choice, the function will validate the chosen input. The problem is when I test the page, none of the alerts pop up, making me conclude that the function isn't even being executed, however the data is being passed to the php page.

<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
		<title>MVC Student Information System - Search</title>
		<script type="text/javascript">
function validate(form){
				if (form.radChoice.value == "S"){
					alert("Branch 1 has executed");
					var strSSN = String(form.SSN.value);
					if (/\b\d{9}\b/.test(strSSN) == false){
						alert("SSN must contain exactly 9 digits");
						return false;
					}
					else{
						return true;
					}
				}
				else if (form.radChoice.value == "N"){
					alert("Branch 2 has executed");
					if (lName.value == NULL || lName.value == ""){
						alert("Name cannot be blank.");
						return false;
					}
					else{
						return true;
					}
				}
				else{
					alert("This should not be happening");
					return false;
				}
			}
</script>
	</head>
	<body>
        <h1>MCV Student Information System</h1>
		<h2>Welcome to the Administrative Add Student Page</h2>
		<h4>Please select a search parameter and click the search button</h4>
		<form action="adminSearch.php" name="search" method="post" 
			onsubmit="return validate(this);">
			<input type="radio" name="radChoice" value="S" />SSN:      <input type="text" name="SSN" /><br>
			<input type="radio" name="radChoice" value="N" />Last Name:<input type="text" name="lName" /><br>
			<input type="submit" name="btnSearch" value="Search" />
		</form>
		<h3><a href="adminMenu.html">Back to Administrative Menu</a></h3>
	</body>
</html>

The call to execute the JS function never occurs. You have coded the html form sentence with: onsubmit="return validate(this);"
which tell the JS parser to return and the execute the function ...

The call to execute the JS function never occurs. You have coded the html form sentence with: onsubmit="return validate(this);"
which tell the JS parser to return and the execute the function ...

onsubmit="return validate(this);" is totally correct (other than the fact that it's generally better to attach event handlers in javascript rather than HTML).

The way to read onsubmit="return validate(this);" is as follows:
After the submit button has been clicked but before actually making the submission, call validate passing this (the form object) as an argument, then return whatever validate returns.
This standard pattern allows a validation function to determine whether the form is submitted (on success we return true) or not (on failure we return false and the form is not sent).

Airshow

Thank you for your help, I will try the .checked attribute for the boolean tests, as well as changing how my if statements occur.

My only other question is why is the function not being called? (At least why are none of the alerts popping up? I am having a similar problem in another page. I had gotten it working, but now I am having the same problem again after changing up the validation for the phone numbers.

I have since moved my JS code into JS files.

//If field is blank
function validate_blank(field, alertMsg){
	with(field){
		if (value == null || value == "") {
			alert(alertMsg);
			return false;
		}
		else {
			return true;
		}
	}
}

// Validate SID field
function validate_SID(field) {
	var strSID = String(field.value);
	if (/\b\d{9}\b/.test(strSID) == false){
		alert("SID must be all digits, no dashes, spaces, or parentheses and must be 9 digits long.");
		return false;
	}
	else{
		return true;
	}
}
		
// Validate State field
function validate_State(field){
	var strState = String(field.value);
	if (/\b[a-z,A-Z]{2}\b/.test(strState) == false){
		alert("State must be in format AA.");
		return false;
	}
	else{
		return true;
	}
}

//Validate Zip Code field
function validate_Zip(field){
	var strZip = String(field.value);
	if (/\b\d{5}\b/.test(strZip) == false){
		alert("Zip Code must be 5 digits");
		return false;
	}
	else{
		return true;
	}
}

//Validate both Phone Number fields
function validate_Phone(field1, field2){
	var strPhone1 = String(field1.value);
	var strPhone2 = String(field2.value);
	
	//Are the fields null?
	var isNull1 = ((strPhone1 == NULL) || (strPhone1 == ""));
	var isNull2 = ((strPhone2 == NULL) || (strPhone2 == ""));
	
	//Are the fields correctly formatted?
	var isCorrect1 = ((/\b[0-9]{10}\b/.test(strPhone1)) ^ (/\b([0-9]{3}-){2}[0-9]{4}\b/.test(strPhone1)));
	var isCorrect2 = ((/\b[0-9]{10}\b/.test(strPhone2)) ^ (/\b([0-9]{3}-){2}[0-9]{4}\b/.test(strPhone2)));
							
	//******** MESSAGE TESTING AREA, REMOVE BEFORE SUBMISSION *********
	var strCorrect1 = String(isCorrect1);
	var strCorrect2 = String(isCorrect2);
	var strNull1 = String(isNull1);
	var strNull2 = String(isNull2);
	alert("isCorrect1 is " + strCorrect1);
	alert("isCorrect2 is " + strCorrect2);
	alert("isNull1 is " + strNull1);
	alert("isNull2 is " + strNull2);
	//*****************************************************************
		
	//If one is null and other is correct, true				
	if ((isNull1 && isCorrect1) || (isCorrect2 && isNull2)){
		return true;
	}
	//If both are correct, true				
	else if(isCorrect1 && isCorrect2){
		return true;
	}
	//Otherwise, false
	else{
		alert("At least one phone number must be filled out.\nPlease use the format XXX-XXX-XXXX or with dashes or without.");
		return false;
	}
}
			
// Validate entire form using preconstructed functions
function validate(this_form){
	with(this_form){
		//Verify the SID meets proper format requirements											
		if(validate_SID(SID) == false){
			return false;
		}
		//Verify First Name is not blank
		else if (validate_blank(fName, "First Name must not be blank.") == false) {
			return false;
		}
		//Verify that Last Name is not blank
		else if (validate_blank(lName, "Last Name must not be blank.") == false) {
			return false;
		}
		//Verify that Address is not blank
		else if (validate_blank(address, "Address must not be blank.") == false) {
			return false;
		}
		//Verify that City is not blank
		else if (validate_blank(city, "City must not be blank.") == false) {
			return false;
		}
		//Verify that State is in proper format 
		else if(validate_State(state) == false){
			return false;
		}
		//Verify that Zip Code is in proper format
		else if(validate_Zip(zip) == false){
			return false;
		}
		//Verify that Home Phone is in proper format
		else if(validate_Phone(hPhone, wPhone) == false){
			return false;
		}
		//If all the data is validated, proceed to PHP file
		else {
			return true;
		}
	}
}
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
		<title>MVC Student Information System - Add Student</title>
		<script type="text/javascript" src="validateAdd.js"></script>
	</head>
	<body>
        <h1>MCV Student Information System</h1>
		<h2>Welcome to the Administrative Add Student Page</h2>
		<form action="adminAdd.php" name="addStudentForm" id="addStudentData" method="post" 
			onsubmit="return validate(this);"
			onreset="return confirm('Clear all fields and reset form?');">
			<table>
				<tr><td>SID:</td><td><input type="text" id="addStudentData" name="SID" /></td><td>(Ex: 123456789)</td></tr>
				<tr><td>First Name:</td><td><input type="text" id="addStudentData" name="fName" /></td></tr>
				<tr><td>Middle Name:</td><td><input type="text" id="addStudentData" name="mName" /></td></tr>
				<tr><td>Last Name:</td><td><input type="text" id="addStudentData" name="lName" /></td></tr>
				<tr><td>Address:</td><td><input type="text" id="addStudentData" name="address" /></td></tr>
				<tr><td>City:</td><td><input type="text" id="addStudentData" name="city" /></td></tr>
				<tr><td>State:</td><td><input type="text" id="addStudentData" name="state" /></td><td>(Ex: AA)</td></tr>
				<tr><td>Zip:</td><td><input type="text" id="addStudentData" name="zip" /></td><td>(Ex: 12345)</td></tr>
				<tr><td>Home Phone:</td><td><input type="text" id="addStudentData" name="hPhone" /></td><td>(Ex: 1234567890 or 123-456-7890)</td></tr>
				<tr><td>Work Phone:</td><td><input type="text" id="addStudentData" name="wPhone" /></td><td>(Ex: 1234567890 or 123-456-7890)</td></tr>
				<tr><td>Show in Directory:</td><td><input type="radio" id="addStudentData" name="showDir" value="y" checked/>Yes 
					<input type="radio" id="addStudentData" name="showDir" value="n"/>No</td></tr>
				<tr><td>Details:</td><td><input type="text" id="addStudentData" name="details" /></td></tr>
			</table>
			<input type="submit" name="Add" id="addStudentData" value="Add" />
			<input type="reset" name="Reset" id="addStudentData" value="Reset" />
			<h3><a href="adminMenu.html">Back to Administrative Menu</a></h3>
		</form>
	</body>
</html>

An explanation: I am essentially checking the phone numbers to allow for the XXX-XXX-XXXX format instead of just the 10 straight digits, as well as allow for one of the fields to be blank

Weasel,

Everything works fine with javascript pasted back into the page but only after addressing NULL. Remember to inspect your javascript error console for error messages.

NULL does not exist. Javascript members are case-sensitive and the null value is "null".

Phone number validation is much more simply achieved by splitting into two functions, a "supervisor" and a "worker". Have the supervisor accept two arguments (phone1 and phone2), then call the worker (with a single argument) for each phone number in turn and aggregate the two returned boolean values. See my sample code below.

I did not check the regular expressions. They appear to work.

"with" is deprecated. validate() is better constructed without "with" and can be simplified.

Consider this:

//Validate a single Phone Number field
function validate_Phone_number(field){
	var strPhone = String(field.value);
	//Is the field null?
	var isNull = ((strPhone == null) || (strPhone == ""));
	//Is the field correctly formatted?
	var isCorrect = ((/\b[0-9]{10}\b/.test(strPhone)) ^ (/\b([0-9]{3}-){2}[0-9]{4}\b/.test(strPhone)));
	return isCorrect && !isNull;
}

//Validate both Phone Number fields
function validate_Phone(field1, field2){
	if ( !validate_Phone_number(field1) && !validate_Phone_number(field2) ){
		alert("At least one phone number must be filled out.\nPlease use the format XXX-XXX-XXXX or with dashes or without.");
		return false;
	}
	else { return true; }
}
			
// Validate entire form using preconstructed functions
function validate(this_form){
	if(!validate_SID(this_form.SID) ||
	   !validate_blank(this_form.fName, "First Name must not be blank.") ||
	   !validate_blank(this_form.lName, "Last Name must not be blank.") ||
	   !validate_blank(this_form.address, "Address must not be blank.") ||
	   !validate_blank(this_form.city, "City must not be blank.") ||
	   !validate_State(this_form.state) ||
	   !validate_Zip(this_form.zip) ||
	   !validate_Phone(this_form.hPhone, this_form.wPhone)) { return false; }
	else { return true; }
}

Taken as a whole, the HTML and javascript are neat and clear. I certainly have no problem seeing what is going on. It's a tidy piece of work.

Airshow

commented: Great advice. Thank you. +3

The NULL -> null issue solved my problem with the function not evaluating. Thanks for your help and your advice.

One question is that I have been looking over your new suggestion for the phone number validation. Will that allow for one of the fields to be blank? I'm only seeing that both fields have to be correct and not null.

One question is that I have been looking over your new suggestion for the phone number validation. Will that allow for one of the fields to be blank? I'm only seeing that both fields have to be correct and not null.

The test if ( !validate_Phone_number(field1) && !validate_Phone_number(field2) ) means that both phone numbers must fail in order for the the overall test to fail. Therefore, if one number passes and one fails, or they both pass, then it validates.

The test can also be written if ( validate_Phone_number(field1) || validate_Phone_number(field2) ) , (either number must pass) which is probably clearer.

Also: I'm not sure but I think the "isNull" test is redundant because an empty string shouldn't pass the "isCorrect" test.

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.