Using jQuery for validations on a registration page

In this tutorial well be using a number of jQuery functions to create a registration page with validations for: Username availability, Password match and Email validation.

Registration page HTML

First of all we need to create a simple registration form using HTML before we start the styling using CSS.

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TutDepot - Form Demonstration</title>
</head>
<body>
<form action="register.php" method="post">
    <fieldset>
        <legend>registration</legend>
        <input type="text" name="username" value="" />
        <label>desired username</label>
        <input type="password" name="password" value="" />
        <label>password</label>
        <input type="password" name="password_again" value="" />
        <label>password Again</label>
        <input type="text" name="email" value="" />
        <label>email</label>
        <input type="submit" name="submit" value="register" />
    </fieldset>
</form>
</body>
</html>

Obviously you can add additional fields such as first name, last name, date of birth and so on if its relevant to your web site.

CSS for the registration form

Next we’re going to write some CSS code to tidy up the form and make it look more attractive.

body { font-family: Arial, Helvetica, sans-serif; width: 500px; }
form fieldset { -moz-border-radius: 6px; -webkit-border-radius: 6px; border: 1px solid #dfe6ee; padding: 10px 15px; }
form fieldset legend { font-size: 22px; }
form fieldset input { margin-bottom: 4px; padding: 3px; font-size: 17px; font-weight: bold; font-family: Arial, Helvetica, sans-serif; color: #51555b; }
form fieldset label { font-weight: bold; padding: 0 0 0 15px; }
form fieldset p.error {
	margin: 0; background: #fdb5b5; -webkit-border-radius-bottomleft: 5px; -moz-border-radius-bottomleft: 5px; -webkit-border-radius-bottomright: 5px; -moz-border-radius-bottomright: 5px;
	border-left: 2px solid #cd4646; border-right: 2px solid #cd4646; border-bottom: 2px solid #cd4646; text-transform: lowercase; font-size: 13px; font-weight: bold;
	display: none; margin: 0 0 5px 0; padding: 4px; width: 200px; }

The main focus of this tutorial are the validation function using PHP and jQuery and we won’t going through the CSS code which is fairly straight forward and self explanatory.

Make sure you have the latest version of jQuery and include it in your script.

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TutDepot - Form Demonstration</title>
<style type="text/css">
@import "styles.css";
</style>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>
<body>
<form action="register.php" method="post" class="register">
    <fieldset>
        <legend>registration</legend>
        <input type="text" name="username" value="" class="username" />
        <label>desired username</label>
		<p class="username_error" style="margin: 0; display: none;">That Username is unavailable</p>
        <input type="password" name="password" value="" />
        <label>password</label>
        <input type="password" name="password_again" value="" />
        <label>password Again</label>
        <input type="text" name="email" value="" />
        <label>email</label>
        <input type="submit" name="submit" value="register" />
    </fieldset>
</form>
</body>
</html>

If you’ve followed the code from this tutorial, your registration form should now look like this.

Registration form example

Username availability

First of all we’re going to write our script to check to see if the desired username is available.

$usernames = array( "martynj", "admin", "bob", "dave", "fred" );
$data = array( "username" => "", "password" => "", "email" => "" );

if( isset($_POST["username"]) ) {
	if( in_array( $_POST["username"], $usernames ) ) {
		$data["username"] = "inuse";
	}
}

This PHP example contains a few random username’s, we use this array only to demonstrate the validation process. In a real worls case you will most likely want to query a MySQL database for this check. Next we check to see if a username has been posted to the script and if the name exists in the usernames array.

The data array containing username, password and email is the array which will be used by query.

Password and e-mail address validation

With the following tests we check if both passwords are the same and we check the e-mail address against a regular expression pattern.

if( isset($_POST["password"]) && isset($_POST["password_again"]) ) {
	if( $_POST["password_again"] != "" && $_POST["password"] != $_POST["password_again"] ) {
		$data["password"] = "missmatch";
	}
}
if( isset( $_POST["email"] ) ) {
	if( $_POST["email"] != "" && !preg_match( "/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST["email"] ) ) {
		$data["email"] = "notvalid";
	}
}

The complete PHP script code (safe this code snippet under the name check.php)

$usernames = array( "martynj", "admin", "bob", "dave", "fred" );
$data = array( "username" => "", "password" => "", "email" => "" );
if( isset($_POST["username"]) ) {
	if( in_array( $_POST["username"], $usernames ) ) {
		$data["username"] = "inuse";
	}
}
if( isset($_POST["password"]) && isset($_POST["password_again"]) ) {
	if( $_POST["password_again"] != "" && $_POST["password"] != $_POST["password_again"] ) {
		$data["password"] = "missmatch";
	}
}
if( isset( $_POST["email"] ) ) {
	if( $_POST["email"] != "" && !preg_match( "/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST["email"] ) ) {
		$data["email"] = "notvalid";
	}
}
echo json_encode( $data );

With every request the array $data is returned as an JSON object.

jQuery error handling

$(document).ready(function(){
	$("form.register").change(function() {
		$.post("check.php", $("form.register").serialize(), function( data ) {
			if( data.username == "inuse" )
				$("p#username_error").slideDown();
			else
				$("p#username_error").hide();
			if( data.password == "missmatch" )
				$("p#password_error").slideDown();
			else
				$("p#password_error").hide();
			if( data.email == "notvalid" )
				$("p#email_error").slideDown();
			else
				$("p#email_error").hide();
		}, "json");
	});
});

Whenever a form element is changed the jQuery code will post the form data to check.php and returns the “data object”. Using three simple if else statements we check if the error messages should be shown of hidden.

Finally we need to put the script together and add the error messages to the form.

The final script

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TutDepot - Form Demonstration</title>
<style type="text/css">
@import "styles.css";
</style>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
	$("form.register").change(function() {
		$.post("check.php", $("form.register").serialize(), function( data ) {
			if( data.username == "inuse" )
				$("p#username_error").slideDown();
			else
				$("p#username_error").hide();
			if( data.password == "missmatch" )
				$("p#password_error").slideDown();
			else
				$("p#password_error").hide();
			if( data.email == "notvalid" )
				$("p#email_error").slideDown();
			else
				$("p#email_error").hide();
		}, "json");
	});
});
</script>
</head>
<body>
<form action="register.php" method="post" class="register">
    <fieldset>
        <legend>registration</legend>
        <input type="text" name="username" value="" />
        <label>desired username</label>
		<p id="username_error" class="error">That Username is unavailable</p>
        <input type="password" name="password" value="" />
        <label>password</label>
        <input type="password" name="password_again" value="" />
        <label>password Again</label>
		<p id="password_error" class="error">Passwords do not match</p>
        <input type="text" name="email" value="" />
        <label>email</label>
        <p id="email_error" class="error">Email is not valid</p>
        <input type="submit" name="submit" value="register" />
    </fieldset>
</form>
</body>
</html>

Check here the jQuery registration demo.