VM Form Validator Tutorial

VMFormValidator is a JavaScript form validation script based on MooTools 1.3. It aims to provide simple, reliable validation for all form element types across all browsers in an unobtrusive manner. It is 100% styled by CSS and allows for custom validations and error messages. Error messages can be displayed above the form, above each input, or below each input. VMFormValidator should not be used as a replacement for server-side validation (using PHP, .NET, etc) because JavaScript can be disabled.

Quick Tutorial

Let's build a quick registration form and validate it. VMFormValidator requires the MooTools library, so we'll need to download the entire MooTools 1.3 Core file. Go download it quickly if you don't already have it. Don't forget to download a copy of VMFormValidator as well.

If you're new to JavaScript (or MooTools), you'll find the implementation of VMFormValidator fairly easy. It's important to note that VMFormValidator has only two requirements for the form: 1) the form must have an id; 2) the form must use labels. Other than that, you're free to style the form however you like. We'll start with constructing our HTML form. For this basic registration form, we're only going to use 4 fields: username, password, passwordConfirm, and email.

<!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=iso-8859-1" />
<title>VMFormValidatorTutorial</title>
</head>

<body>
	<form id="registration" method="post" action="">
		<label for="username">Username</label>
		<input id="username" name="username" type="text" />
		<label for="password">Password</label>
		<input id="password" name="password" type="password" />
		<label for="confirmPassword">Confirm Password</label>
		<input id="confirmPassword" name="confirmPassword" type="password" />
		<label for="email">Email</label>
		<input id="email" name="email" type="text" />
		<input type="submit" value="Submit" />
	</form>
</body>
</html>

That was pretty easy, right? Let's go ahead and add just a little CSS styling to make our form look better (though we won't go overboard). For this tutorial, we're just going to put it in the head of our XHTML document, but in practice we recommend putting in your stylesheet in a separate file.

<style type="text/css">
	input, label, .errorList {float:left; clear:left;}
</style>

Next we need to add our JavaScript files, MooTools1.2-core.js and VMFormValidator1.0.js. We'll put those in the document head as well.

<script type="text/javascript" src="mootools-1.2-core.js"></script>
<script src="VMFormValidator1.0.js" type="text/javascript"></script>

Now we need to add a little bit of MooTools specific JavaScript. MooTools has a special event called 'domready' that executes whenever the HTML has finished loading. Most MooTools scripts are at least partially executed from within the 'domready' event. Again, we're just going to put this code in the document head, but it could also be in its own file.

<script type="text/javascript">
	window.addEvent('domready', function(){
		//Our validation code will go here
	});
</script>

All of our validation code is going to be inserted into the 'domready' event, right where the comment currently is. The first thing we'll need to do is initialize the VMFormValidator class. In this case, we'll use the variable form, but you can use register, or form1, or whatever you like. We'll set form equal to a new instance of VMFormValidator. Because the constructor for the VMFormValidator class has one required argument, the form id, we're going to enter in our form id of 'registration', surrounded in quotes to make it a string.

<script type="text/javascript">
	window.addEvent('domready', function(){
		var form = new VMFormValidator('registration');
	});
</script>

The constructor for VMFormValidator also has an optional argument for options, but we'll cover that a little later. Next, we're going make all of our form fields required. To do that, we'll use VMFormValidator's required method. The required method has one required argument, the field name we want to be required, and one optional argument, the error. Almost every method has a default error that it displays, but we can customize it if we want. We'll customize it only for the username and password fields.

<script type="text/javascript">
	window.addEvent('domready', function(){
		var form = new VMFormValidator('registration');
		form.required('username', 'Please enter a username.'); //Custom error
		form.required('password', 'Please enter a password.'); //Custom error
		form.required('confirmPassword'); //Default error
		form.required('email');	//Default error			
	});
</script>

Go ahead and try out your script now. It should be validating for each field, with an error message appearing below each input element if you don't type in it. If there are any problems, check to make sure that the paths to your javascript files are correct and that each one of the arguments entered above are in string format. While we're on the subject of arguments, if you look closely at the documentation, you'll see that VMFormValidator uses 3 other kinds of arguments: boolean (which is either true or false), integer (a whole number), and object (usually in an array format).

Let's add a few more validations to our form. For the username field, we'll add alphanumeric and range. For the password field, we'll add noMatches and password. For confirmPassword, we'll add matches, and for email, we'll add email.

<script type="text/javascript">
	window.addEvent('domready', function(){
		var form = new VMFormValidator('registration');
		form.required('username', 'Please enter a username.'); //Custom error
		form.alphanumeric('username'); //Default error
		form.range('username', 4, 10) //Default error
		form.required('password', 'Please enter a password.'); //Custom error
		form.noMatches('password', 'username', 'The password and username cannot be the same.'); //Custom Error
		form.password('password'); //Default error
		form.required('confirmPassword'); //Default error
		form.matches('confirmPassword', 'password', 'Passwords must match.'); //Custom error
		form.required('email');	//Default error
		form.email('email'); //Default error			
	});
</script>

That's all there is to it! Try your form again and try to sneak past it (without disabling JavaScript). We could stop there, but I'll show you just a few more things VMFormValidator can do.

Like I mentioned earlier, VMFormValidator has options. The default CSS class names VMFormValidator uses are .successLabel, .successElement, .errorLabel, .errorElement, .errorList, and .errorListItem. Let's add a little more style to our form by adding to our CSS:

<style type="text/css">
	input, label, .errorList {float:left; clear:left;}
	.successLabel {color:#006600;}
	.successElement {border:#006600 1px solid;}
	.errorLabel, .errorListItem {color:#FF0000;}
	.errorElement {border:#FF0000 1px solid;}	
</style>

If you don't like the class names VMFormValidator uses, you can change them by specifying them in the class constructor. To do that, we're going to use our optional argument for the VMFormValidator contructor method. Because the optional argument accepts more than one option, we need to enclose it in an object. That simply means we'll put curly braces {} around our entire set of options. Each option has two parts: the option name and its value, which are separated by a colon. If you have more than one option, each option should be separated by a comma, except the last one. Sound complicated? It's actually easier than it sounds. Let's take a look at an example:

<script type="text/javascript">
	window.addEvent('domready', function(){
		var form = new VMFormValidator('registration', {
			disableSubmit: false,
			errorDisplay: 'aboveForm'
		});
		form.required('username', 'Please enter a username.'); //Custom error
		form.alphanumeric('username'); //Default error
		form.range('username', 4, 10) //Default error
		form.required('password', 'Please enter a password.'); //Custom error
		form.noMatches('password', 'username', 'The password and username cannot be the same.'); //Custom Error
		form.password('password'); //Default error
		form.required('confirmPassword'); //Default error
		form.matches('confirmPassword', 'password', 'Passwords must match.'); //Custom error
		form.required('email');	//Default error
		form.email('email'); //Default error			
	});
</script>

The above code tells VMFormValidator that the submit button should not be disabled if there is an error and that all errors should be displayed above the form. The CSS classes can be specified in the same way if you don't like the defaults. For a full list of options, see the constructor method.

With that, our tutorial draws to a close. If you want to dig deeper into VMFormValidator, the documentation below provides examples for each method, along with the method syntax and argument types. I hope VMFormValidator will be a worthy solution for your forms. If you encounter a bug, have a question or comment, feel free to contact us. If you liked VMFormValidator, tell someone else about it. Thanks, and enjoy!

Tags

  • Benjamin Kuker

    Benjamin Kuker

    Benjamin Kuker is the co-founder of Virtuosi Media and is married to his beautiful wife, Johanna. He is responsible for the design and maintenance of this website. He enjoys reading, writing, programming, business, sports, and traveling.

    View Benjamin's Bio

Help us spread the word.

Your Comments Are Valuable - Join The Discussion!

 

Copyright 2011 Virtuosi Media Inc.