Jump to content

My First Form Validation Script


hybrid kill3r
 Share

Recommended Posts

I just finished writing my first form validation script... well I guess it's not finished since it won't work. I press the submit button but the form submits, even though all the info is invalid. My javascript code:

// JavaScript Documentfunction validate_form(){		 if (window.XMLHttpRequest) {		http = new XMLHttpRequest();	} else if (window.ActiveXObject) {		http = new ActiveXObject("Microsoft.XMLHTTP");	}	handle = document.getElementById(userid);	var url = '../classes/register.php?';		<!-- Check Username existance ->	if(handle.value.length > 0) {		var fullurl = url + 'do=username_check&username=' + encodeURIComponent(handle.value);		http.open("GET", fullurl, true);		http.send(null);		http.onreadystatechange = statechange_username;	}else{		document.getElementByID('username').innerHTML = '';	}	 if (http.readyState == 4) {		var xmlObj = http.responseXML;		var usernamehtml = xmlObj.getElementsByTagName('username').item(0).firstChild.data;	 }	 	 <!-- Check Email ->	 	 if(handle.value.length > 0) {		var fullurl = url + 'do=email_check&email=' + encodeURIComponent(handle.value);		http.open("GET", fullurl, true);		http.send(null);		http.onreadystatechange = statechange_username;	}else{		document.getElementByID('username').innerHTML = '';	}	 	 if (http.readyState == 4) {		var xmlObj = http.responseXML;		var emailhtml = xmlObj.getElementsByTagName('email').item(0).firstChild.data;	 }	 	 //Check security code	 if(handle.value.length > 0) {		var fullurl = url + 'do=securitycode&code=' + encodeURIComponent(handle.value);		http.open("GET", fullurl, true);		http.send(null);		http.onreadystatechange = statechange_username;	}else{		document.getElementByID('securityCode').innerHTML = '';	}	 	 if (http.readyState == 4) {		var xmlObj = http.responseXML;		var securityhtml = xmlObj.getElementsByTagName('security').item(0).firstChild.data;	 }	 	 //Check form elements	 	 if (document.getElementsByName('pass') != document.getElementsByName('confirm')){		document.getElementsByID('form_errors').innerHTML = "The passwords you entered do not match.";		return FALSE;	 }	 var pass = document.getElementsByID('pass');	 if(pass.length > 15){		 document.getElementsByID('form_errors').innerHTML = "The password you entered is too short.";		 return FALSE;	 }	 if(pass.length < 4){		 document.getElementsByID('form_errors').innerHTML = "The password you entered is too long.";		 return FALSE;	 }	 	 if(usernamehtml == "The username is already in use."){		document.getElementsById('form_errors').innerHTML = usernamehtml;		return FALSE;	 } 	 if(usernamehtml == "The display name must be greater than 4 and less than 15."){		 document.getElementsById('form_errors').innerHTML = emailhtml;		 return FALSE;	 } 	 if(emailhtml == "There is already an account registered with this email address."){		 document.getElementsById('form_errors').innerHTML = emailhtml;		 return FALSE;	 } 	 if(emailhtml == "You did not enter a valid email address."){		 document.getElementsById('form_errors').innerHTML = emailhtml;		 return FALSE;	 }	 if(securityhtml == "The security code you entered is incorrect."){		 document.getElementsById('form_errors').innerHTML = securityhtml;		 return FALSE;	 }	 }

My form code:

<div id='stats'>	<ul id='form_errors'>	</ul>		<table align='center' cellspacing='1' cellpadding='0' border='0' width='100%'>			<tr><form action='ACTION' method='POST' onsubmit="validate_form()" name='register'>				<td align='center' colspan='2' class='category_top'>Create an Account</td>			</tr><tr>				<td align='right'>Display Name: </td>				<td align='left'><input id="username" type="text" name="username" size='30'/></td>			</tr><tr>				<td align='right'>Email Address: </td>				<td align='left'><input id="email" type="text" name="email" size='30'/></td>			</tr><tr>				<td align='right'>Password: </td>				<td align='left'><input type='password' id='pass' name='pass' size='30'/></td>			</tr><tr>				<td align='right'>Confirm Password: </td>				<td align='left'><input type='password' name='confirm' size='30' /></td>			</tr><tr>				<td align='right'>Security Code: <br /><small>Enter the random security code to proove that you are human.</small><br />				<img src='classes/captcha.php' alt='security code' border='1' /></td>				<td align='left' style='vertical-align: top;'><input type='text' name='securitycode' size='30' /></td>			</tr><tr>				<td align='center' colspan='2'><input type='submit' value='Join!' name='submit' /></td>			</tr></form>		</table> </div>

Ajax.php

<?php$do = $_GET['do'];switch($do){		case "username_check":		$username = $_GET['username'];		$query = mysql_query("SELECT * FROM members WHERE displayname = '".$username."'") or die("Validation1: ".mysql_error());		header('Content-Type: text/xml');		header('Pragma: no-cache');		echo '<?xml version="1.0" encoding="UTF-8"?>';		echo '<username>';		if(mysql_num_rows($query) != 0){			echo "<li>The username is already in use.</li>";		} elseif(($username < 4) || ($username > 15)){			echo "<li>The display name must be greater than 4 and less than 15.</li>";		} 		echo "</username>";			break;		case "email_check":				$email = $_GET['email'];		$query = mysql_query("SELECT * FROM members WHERE email = '".$email."'") or die("Validation2: ".mysql_error());		header('Content-Type: text/xml');		header('Pragma: no-cache');		echo '<?xml version="1.0" encoding="UTF-8"?>';		echo '<email>';		if(mysql_num_rows($query) != 0){			echo '<li>There is already an account registered with this email address.</li>';		} elseif(!preg_match("@", $email)){			echo '<li>You did not enter a valid email address.</li>';		} elseif(!preg_match(".", $email)){			echo "<li>You did not enter a valid email address.</li>";		}		echo "</email>";			break;		case "securitycode":			$securitycode = $_GET['code'];		header('Content-Type: text/xml');		header('Pragma: no-cache');		echo '<?xml version="1.0" encoding="UTF-8"?>';		echo '<security>';		if($securitycode != $_SESSION['securityCode']){			echo "The security code you entered is incorrect.";		}		echo '</security>';			break;		default: 			echo "Invalid action.";		}?>

What it's supposed to do is request the ajax php code from the server, validate the username, email, password, and security code and update the form errors unordered list in the form body. Then it returns false. If nothing is true, shouldn't it not submit?

Edited by Hybrid Kill3r
Link to comment
Share on other sites

You're not using ajax correctly. You can't send a request and check the response in the same function. It's also not going to be very efficient to send each individual thing to check as its own request, just send one request with all information and check it all at once, and send back error messages for various fields. If there are no error messages sent back, then you can submit the form.So you need one function to gather the form information and send the request, which will always return false to stop the form from submitting, and then a second function to process the response that comes back where you decide whether or not to submit the form.Also, your form tag is in the wrong place. You start the form inside a tr element and end it between a closing tr tag and closing table tag. Just wrap the entire table in the form, don't put the starting form tag somewhere in the table and the ending tag somewhere else, that's not structured correctly.

Edited by justsomeguy
Link to comment
Share on other sites

I think I managed to clean up my JavaScript code quite a bit. I also fixed the ajax.php file to check everything in one case. The only problem is that I'm not really sure where to have the script submit the form info and where to have it display the errors. Here's my new JS file:

function validate_form(){		 if (window.XMLHttpRequest) {		http = new XMLHttpRequest();	} else if (window.ActiveXObject) {		http = new ActiveXObject("Microsoft.XMLHTTP");	}	handle = document.getElementById(userid);	displayname = document.getElementByName(displayname);	email = document.getElementByName(email);	pass = document.getElementByName(pass);	conf = document.getElementByName(confirm);	security = document.getElementByName(secruitycode);	var url = '../classes/ajax.php?';		<!-- Check Username existance ->   if(handle.value.length > 0) {		var fullurl = url + 'do=check_info&displayname=' + encodeURIComponent(handle.value) + "&pass=" + encodeURIComponent(pass.value) + "&confirm=" + encodeURIComponent(conf.value) + "&securitycode=" + encodeURIComponent(security.value);		http.open("GET", fullurl, true);		http.send(null);		http.onreadystatechange = statechange_username;	}else{		document.getElementByID('username').innerHTML = '';	}}function statechange_username() {	if (http.readyState == 4) {		document.register.submit();	} else {		var xmlObj = http.responseXML;		var html = xmlObj.getElementsByTagName('errors').item(0).firstChild.data;		document.getElementById('form_errors').innerHTML = html;	}}

And my new ajax.php file:

<?php$do = $_GET['do'];switch($do){		case "check_info":		$form = array(					  'displayname' => $_GET['displayname'],					  'email' => $_GET['email'],					  'pass' => $_GET['pass'],					  'confirm' => $_GET['confirm'],					  'securitycode' => $_GET['securitycode']					  );		$query = mysql_query("SELECT * FROM members WHERE displayname = '".$form['displayname']."'") or die("Validation1: ".mysql_error());		header('Content-Type: text/xml');		header('Pragma: no-cache');		echo '<?xml version="1.0" encoding="UTF-8"?>';		echo '<errors>';		if(mysql_num_rows($query) != 0){			echo "<li>The username is already in use.</li>";		} elseif(($username < 4) || ($username > 15)){			echo "<li>The display name must be greater than 4 and less than 15.</li>";		} 				if(!$form['pass']){			echo "<li>You must enter a password.</li>";		} elseif($form['pass'] != $form['confirm']){			echo "<li>The passwords do not match.</li>";		} elseif(strlen($form['pass']) < 4){			echo "<li>The password is less than four characters in length.</li>";		} elseif(strlen($form['pass']) > 15){			echo "<li>The password is greater than 15 characters in length.</li>";		}		$query = mysql_query("SELECT * FROM members WHERE email = '".$form['email']."'") or die("Validation2: ".mysql_error());		if(mysql_num_rows($query) != 0){			echo '<li>There is already an account registered with this email address.</li>';		} elseif(!preg_match("@", $form['email'])){			echo '<li>You did not enter a valid email address.</li>';		} elseif(!preg_match(".", $form['email'])){			echo "<li>You did not enter a valid email address.</li>";		}				$securitycode = $_GET['code'];		if(!$securitycode){			echo "<li>You did not enter a security code.</li>";		} elseif($form['securitycode'] != $_SESSION['securityCode']){			echo "<li>The security code you entered is incorrect.</li>";		}		echo '</errors>';			break;		default: 			echo "Invalid action.";			break;		}?>

Link to comment
Share on other sites

Everything happens in the statechange function. You have one function to gather the data and send the request, which needs to return false to cancel the form submission, and then the function that handles the response from the server needs to check if there are any error messages and submit the form if necessary.

Link to comment
Share on other sites

It's fine if you only send the request if the username is non-empty, but you'll want to put something in the else to print a message saying that. It's submitting because you don't have the function returning false to cancel the submit.

Link to comment
Share on other sites

You're probably getting iritated, but I do have it returning false now and it still submits.

function validate_form(){		 if (window.XMLHttpRequest) {		http = new XMLHttpRequest();	} else if (window.ActiveXObject) {		http = new ActiveXObject("Microsoft.XMLHTTP");	}	displayname = document.getElementByID(displayname);	email = document.getElementByID(email);	pass = document.getElementByID(pass);	conf = document.getElementByID(confirm);	security = document.getElementByID(secruitycode);	var url = 'classes/ajax.php?';		var fullurl = url + 'do=check_info&displayname=' + encodeURIComponent(handle.value) + "&pass=" + encodeURIComponent(pass.value) + "&confirm=" + encodeURIComponent(conf.value) + "&securitycode=" + encodeURIComponent(security.value);		http.open("GET", fullurl, true);		http.send(null);		http.onreadystatechange = statechange_username;		return FALSE;}function statechange_username() {	if (http.readyState == 4) {		var xmlObj = http.responseXML;		var html = xmlObj.getElementsByTagName('errors').item(0).firstChild.data;		if(!html.value){			document.getElementById('form_errors').innerHTML = html;		} else {			document.register.submit();		}	}}

Link to comment
Share on other sites

Seems to be working for me:

<html>  <head>	<title>test</title>	<script type="text/javascript">	function stop_submit()	{	  return false;	}	</script>  </head>  <body>	<form onsubmit="return stop_submit();">	  <input type="submit" name="submit" value="Submit">	</form>  </body></html>

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...