Jump to content

Form Validation


himesh
 Share

Recommended Posts

I have modified a form validation code I have used before. It highlights the fields that are incorrect and a popup shows the user which ones need to be corrected. An example is here .I need this to happen with my php website but when I run it, the errors go to the address bar instead and the yellow box fades after a second. This is my code, it can tell there are incorrect fields but does not tell me which they are and why they are incorrect.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><script type="text/javascript">function validateFormOnSubmit(register) {var reason = "";  reason += validateUsername(register.Username);  reason += validatePassword2(register.Password2);  reason += validateName(register.Firstname);  reason += validateSurname(register.Surname);  reason += validateAddress(register.Address);  reason += validateAddress2(register.Address2);  reason += validateTown(register.Town);  reason += validateCounty(register.County);  reason += validatePostcode(register.Postcode);  reason += validateEmail(register.Email);  reason += validatePhone(register.Phone);	    if (reason != "") {	alert("Some fields need correction:\n" + reason);	return false;  }  alert("All fields are filled correctly, please feel free to browse the rest of our website.");  return false;  }function validateUsername(fld) {	var error = "";	var illegalChars = /\W/; // allow letters, numbers, and underscores 	if (fld.value == "") {		fld.style.background = 'Yellow'; 		error = "You didn't enter a username.\n";	} else if (illegalChars.test(fld.value)) {		fld.style.background = 'Yellow'; 		error = "Are you sure your name contains non letters?.\n";	} else {		fld.style.background = 'White';	}	return error;}  function validatePassword2(fld) {	var error = "";	var illegalChars = /\W/; // allow letters, numbers, and underscores 	if (fld.value != register.Password) {		fld.style.background = 'Yellow'; 		error = "Your passwords do not match.\n";	} else {		fld.style.background = 'White';	}	return error;}function validateName(fld) {	var error = "";	var illegalChars = /\W/; // allow letters, numbers, and underscores 	if (fld.value == "") {		fld.style.background = 'Yellow'; 		error = "You didn't enter your first name.\n";	} else if (illegalChars.test(fld.value)) {		fld.style.background = 'Yellow'; 		error = "Are you sure your name contains non letters?.\n";	} else {		fld.style.background = 'White';	}	return error;}		function validateSurname(fld) {	var error = "";	var illegalChars = /\W/; // allow letters, numbers, and underscores 	if (fld.value == "") {		fld.style.background = 'Yellow'; 		error = "You didn't enter your surname.\n";	} else if (illegalChars.test(fld.value)) {		fld.style.background = 'Yellow'; 		error = "Are you sure your surnamename contains non letters?.\n";	} else {		fld.style.background = 'White';	}	return error;}function validateAddress(fld) {	var error = "";	var illegalChars = /\W/; // allow letters, numbers, and underscores 	if (fld.value == "") {		fld.style.background = 'Yellow'; 		error = "You didn't enter your address.\n";	} 	return error;}function validateAddress2(fld) {	var error = "";	var illegalChars = /\W/; // allow letters, numbers, and underscores 	if (fld.value == "") {		fld.style.background = 'Yellow'; 		error = "You didn't enter your address.\n";	} 	return error;}function validateTown(fld) {	var error = "";	var illegalChars = /\W/; // allow letters, numbers, and underscores 	if (fld.value == "") {		fld.style.background = 'Yellow'; 		error = "You didn't enter your town.\n";	} 	return error;}function validatePostcode(fld) {	var error = "";	var illegalChars = /\W/; // allow letters, numbers, and underscores 	if (fld.value == "") {		fld.style.background = 'Yellow'; 		error = "You didn't enter your postcode.\n";	} 	return error;}function validateEmail(fld) {	var error="";	var tfld = trim(fld.value);						// value of field with whitespace trimmed off	var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/;	var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/;   	if (fld.value == "") {		fld.style.background = 'Yellow';		error = "You didn't enter an email address.\n";	} else if (!emailFilter.test(tfld)) {			  //test email for illegal characters		fld.style.background = 'Yellow';		error = "Please enter a valid email address.\n";	} else if (fld.value.match(illegalChars)) {		fld.style.background = 'Yellow';		error = "The email address contains illegal characters.\n";	} else {		fld.style.background = 'White';	}	return error;}function validatePhone(fld) {	var error = "";	var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');	   if (fld.value == "") {		error = "You didn't enter a phone number.\n";		fld.style.background = 'Yellow';	} else if (isNaN(parseInt(stripped))) {		error = "The phone number contains illegal characters.\n";		fld.style.background = 'Yellow';	} else if (stripped.length != 11) {		error = "The phone number is the wrong length. Make sure you included an area code.\n";		fld.style.background = 'Yellow';	}	  else {		  fld.style.background ='White';	  }	return error;}</script><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Communicate - the best in mobile communications</title><link rel="stylesheet" type="text/css" href="_css/main.css" /><link rel="stylesheet" type="text/css" href="_css/style.css" />	<script src="jquery-1.2.1.min.js" type="text/javascript"></script>	<script src="menu.js" type="text/javascript"></script><!--[if IE]><style type="text/css"> /* place css fixes for all versions of IE in this conditional comment */.thrColElsHdr #sidebar1, .thrColElsHdr #sidebar2 { padding-top: 30px; }.thrColElsHdr #mainContent { zoom: 1; padding-top: 15px; }/* the above proprietary zoom property gives IE the hasLayout it needs to avoid several bugs */</style><![endif]--></head><body class="thrColElsHdr"><div id="container">  <div id="header">   <div id="search">   </div>     <!-- end #header -->  </div>      <div id="sidebar1"><ul id="menu">						<li><a href="http://www.himeshs.co.uk/communicate/index.php">Home</a></li>									 														<li>							<a href="#">Manufacturer</a>							<ul> 							  <li><a href="http://www.himeshs.co.uk/communicate/allmanufacturer.php">All</a></li> 							<li><a href="http://www.himeshs.co.uk/communicate/apple.php">Apple</a></li> 						   	<li><a href="http://www.himeshs.co.uk/communicate/lg.php">LG</a></li> 							<li><a href="http://www.himeshs.co.uk/communicate/nokia.php">Nokia</a></li> 							<li><a href="http://www.himeshs.co.uk/communicate/samsung.php">Samsung</a></li> 							<li><a href="http://www.himeshs.co.uk/communicate/se.php">Sony Ericsson</a></li> 							</ul> 						</li>													 <li>							<a href="#">Type</a>								<ul> 							<li><a href="http://www.himeshs.co.uk/communicate/alltype.php">All</a></li> 							<li><a href="http://www.himeshs.co.uk/communicate/slide.php">Slide</a></li> 							<li><a href="http://www.himeshs.co.uk/communicate/candy.php">Candy Bar</a></li> 							<li><a href="http://www.himeshs.co.uk/communicate/flip.php">Flip</a></li>					  							</ul> 	  </li>																  <li>							<a href="#">Features</a>							<ul> 							<li><a href="http://www.himeshs.co.uk/communicate/camera.php">Camera</a></li> 							<li><a href="http://www.himeshs.co.uk/communicate/music.php">Music</a></li> 							<li><a href="http://www.himeshs.co.uk/communicate/internet.php">Internet</a></li>												  							</ul> 						</li>									<li><a href="http://www.himeshs.co.uk/communicate/aboutus.php">About us</a></li>							<li><a href="http://www.himeshs.co.uk/communicate/contact.php">Contact us</a></li>	</ul>  <!-- end #sidebar1 -->  </div>      <div id="sidebar2">      <!-- end #sidebar2 --></div>      <div id="mainContent">	<h1> Register</h1>	<p align="left">Please fill out the form below to register for an account</p>	<form name="register" onSubmit="return validateFormOnSubmit(this)" action="">	<table border="0">	  <tr>	  <td colspan="2">		<div align="right">* Denotes a required field </div></td>	  </tr>	  <tr>		<td>Username</td>		<td><label>		  <input type="text" name="Username" id="Username" />		</label></td>		<td>*</td>	  </tr>	  <tr>		<td>Password</td>		<td><label>		  <input type="password" name="Password" id="Password" />		</label></td>		<td>*</td>	  </tr>	  <tr>		<td>Password</td>		<td><label>		  <input type="password" name="Password2" id="Password2" />		</label></td>		<td>*</td>	  </tr>	  <tr>		<td colspan="2"><div align="center">----------------------------------------</div></td>		<td> </td>	  </tr>	  <tr>		<td>Title</td>		<td><label>		  <select name="Title" id="Title">			<option selected="selected">Mr</option>			<option>Mrs</option>			<option>Ms</option>			<option>Dr</option>			<option>Sir</option>			<option>Rev</option>		  </select>		</label></td>		<td>*</td>	  </tr>	  <tr>		<td>First Name</td>		<td><input type="text" name="Firstname" id="Firstname" /></td>		<td>*</td>	  </tr>	  <tr>		<td>Surname</td>		<td><input type="text" name="Surname" id="Surname" /></td>		<td>*</td>	  </tr>	  <tr>		<td>Address</td>		<td><input type="text" name="Address" id="Address" /></td>		<td>*</td>	  </tr>	   <tr>		<td>Address 2</td>		<td><input type="text" name="Address2" id="Address2" /></td>		<td> </td>	  </tr>	   <tr>		<td>Town</td>		<td><input type="text" name="Town" id="Town" /></td>		<td>*</td>	  </tr>	   <tr>		<td>County</td>		<td><input type="text" name="County" id="County" /></td>		<td>*</td>	  </tr>	   <tr>		<td>Postcode</td>		<td><input type="text" name="Postcode" id="Postcode" /></td>		<td>*</td>	  </tr>	   <tr>		<td colspan="2"><div align="center">----------------------------------------</div></td>		<td><div align="center"></div></td>	  </tr>	   <tr>		<td>Email Address</td>		<td><input type="text" name="Email" id="Email" /></td>		<td>*</td>	  </tr>	   <tr>		<td>Phone Number</td>		<td><input type="text" name="Phone" id="Phone" /></td>		<td> </td>	  </tr>	   <tr>		<td> </td>		<td> </td>		<td> </td>	  </tr>	   <tr>		<td><label>		  <div align="center">			<input type="reset" name="reset" id="reset" value="Reset" />		  </div>		</label></td>		<td><div align="center">		  <input type="submit" name="Submit" id="Submit" value="Submit" />		</div></td>		<td> </td>	  </tr>	</table>	</form>	<p align="left">.</p>	<!-- end #mainContent -->  </div>		<!-- This clearing element should immediately follow the #mainContent div in order to force the #container div to contain all child floats --><br class="clearfloat" />   <div id="footer">	<p>Footer</p>  <!-- end #footer --></div><!-- end #container --></div></body></html>

Link to comment
Share on other sites

When the form loads, it is on the register.php page. When the validation processes, the address bar changes to the following.../register.php?Username=&Password=&Password2=&Title=Mr&Firstname=&Surname=&Address=&Address2=&Town=&County=&Postcode=&Email=&Phone=&Submit=Submit

Link to comment
Share on other sites

Ive changed my validation to the following but I have tried to add a field which checks whether the two passwords match. When I tried verifying it, with no results, it says that the passwords do not match but when they are completely different, they are accepted and the rest of the form validated. I also want to add the forms validated results into the user table, this is to be done via an sql command which will be hosted on another page, the action in the form must be pointed to this? So something on the lines of this

<form onsubmit='return formValidator()' action='adduser.php'>

Here is my new code which does not like the password field. Can anybody spot the error?

<script type="text/javascript">function formValidator(){		var username = document.getElementById('username');	var password = document.getElementById('password');	var firstname = document.getElementById('firstname');	var surname = document.getElementById('surname');	var address = document.getElementById('address');	var town = document.getElementById('yown');	var county = document.getElementById('county');	var postcode = document.getElementById('postcode');	var email = document.getElementById('email');	var phone = document.getElementById('phone');	if(lengthRestriction(username, 6, 10)){	if(passwordCheck(password, "Your passwords do not match")){			if(isAlphabet(firstname, "Please enter only letters for your name")){				if(isAlphabet(surname, "Please enter only letters for your surname")){					if(isAlphanumeric(address, "Please enter only numbers and letters for your address")){						if(isAlphabet(town, "Please enter only letters for your Town")){							if(isAlphabet(county, "Please enter only letters for your County")){								if(lengthRestriction(postcode, 6, 7)){									if(emailValidator(email, "Please enter a valid email address")){										if(isNumeric(phone, "Please enter a valid phone number")){											return true;										}									}								}							}						}					}				}			}		}	}return false;}function passwordCheck(elem, helperMsg){		var password2 = document.getElementById('password2');	if(elem.value.match(password2)){		return true;	}else{		alert(helperMsg);		elem.focus();		return false;	}	return true;}	function notEmpty(elem, helperMsg){	if(elem.value.length == 0){		alert(helperMsg);		elem.focus(); // set the focus to this input		return false;	}	return true;}function isNumeric(elem, helperMsg){	var numericExpression = /^[0-9]+$/;	if(elem.value.match(numericExpression)){		return true;	}else{		alert(helperMsg);		elem.focus();		return false;	}}function isAlphabet(elem, helperMsg){	var alphaExp = /^[a-zA-Z]+$/;	if(elem.value.match(alphaExp)){		return true;	}else{		alert(helperMsg);		elem.focus();		return false;	}}function isAlphanumeric(elem, helperMsg){	var alphaExp = /^[0-9a-zA-Z]+$/;	if(elem.value.match(alphaExp)){		return true;	}else{		alert(helperMsg);		elem.focus();		return false;	}}function lengthRestriction(elem, min, max){	var uInput = elem.value;	if(uInput.length >= min && uInput.length <= max){		return true;	}else{		alert("Please enter between " +min+ " and " +max+ " characters");		elem.focus();		return false;	}}function madeSelection(elem, helperMsg){	if(elem.value == "Please Choose"){		alert(helperMsg);		elem.focus();		return false;	}else{		return true;	}}function emailValidator(elem, helperMsg){	var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;	if(elem.value.match(emailExp)){		return true;	}else{		alert(helperMsg);		elem.focus();		return false;	}}		</script>

Link to comment
Share on other sites

Well, I think I know why your password validation isn't working. You're comparing an element to a string. That's not going to work.

function passwordCheck(elem, helperMsg){		var password2 = document.getElementById('password2').value; //Get a reference to the VALUE instead of the element		if(elem.value.match(password2)){				return true;		}else{				alert(helperMsg);				elem.focus();				return false;		}		return true;}

I'm not sure about the match() method. But you could just do it this way:if (elem.value == password2) {and that will get you the same result.

Link to comment
Share on other sites

I have changed my code to this and now and it keeps going down the else route and displaying the error message.

function passwordCheck(elem, helperMsg){		var password2 = document.getElementById('password2');	if(elem.value == password2){		return true;	}else{		alert(helperMsg);		elem.focus();		return false;	}	return true;}

I have also tried putting the password2 in '' and ('') but still to no avail, any more suggestions?

Link to comment
Share on other sites

Thanks that worked a treat. The final validation on this form is to see whether that username exists. I have done this via an sql statement.

mysql_select_db($database_conn_comm, $conn_comm);$query_usernamecheck = sprintf("SELECT username FROM tbluser WHERE username = %s", GetSQLValueString($colname_usernamecheck, "text"));$usernamecheck = mysql_query($query_usernamecheck, $conn_comm) or die(mysql_error());$row_usernamecheck = mysql_fetch_assoc($usernamecheck);$totalRows_usernamecheck = mysql_num_rows($usernamecheck);if($totalRows_usernamecheck !== 0){		 die("Sorry! The user exists already");}

Is there anyway that this can check this and report it back to the user on the page as opposed to on the next page by itself?

Link to comment
Share on other sites

I managed to get the desired result with this...

if($totalRows_usernamecheck !== 0){		echo '<script type="text/javascript">alert("Sorry that username has been taken");</script>'; }

Now I just need to get the data to insert into the table,

Link to comment
Share on other sites

When adding to the database, I have used this

<form onsubmit='return formValidator()' action="adduser.php" method="post">

which will automatically run the script (which successfully adds to the database) and is ignoring the validation. How can I make sure that the adduser.php will only be accessed if the validation has been successful?

Link to comment
Share on other sites

In order to cancel the submission the submit handler needs to return false. If it returns any other value or doesn't return anything the form will submit.It's also a good idea to validate everything in PHP also even if you also validate with Javascript. You can't guarantee that the Javascript will even execute, so make sure you validate everything in PHP. Javascript is just a convenience for the user, it shouldn't be relied on to make sure the data is correct though.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...