VMFormValidator - Form Validation Using MooTools

Contents

Demos

Description

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.

License

VMFormValidator is released under the open-source MIT License.

Features

Dependencies

VMFormValidator requires the MooTools JavaScript framework. Specifically, it requires the complete MooTools Core (but not MooTools More) file.

A 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.2 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!

Documentation

Class: VMFormValidator

This class is for validating forms.

Implements:

Notes:

VMFormValidator Method: constructor

VMFormValidator is completely unobtrusive and requires no changes to existing markup, provided the form has an id and uses labels.

Syntax:

var form = new VMFormValidator(formId[, options]);

Arguments:

  1. formId - (string) The id of the form on which validation should be performed.
  2. options - (object, optional) Any of the options below.

Options:

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
});

Notes:

VMFormValidator Method: addFunction

Adds a custom function to the onBlur and onSubmit events, to be run with the rest of the validations.

Syntax:

form.addFunction(name, customFunction);

Arguments:

  1. name - (string) The name of the form element to which the custom function should be applied.
  2. customFunction - (string) The function which should be applied for both onBlur and onSubmit events (if they are enabled) for the form element. The customFunction must be in string format because it is later executed using eval.

Example:

var custom_function = function(){
	alert('This is a custom function');
}

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.addFunction('firstName', 'custom_function()');
});

Notes:

VMFormValidator Method: alpha

Validates alphabetic characters.

Syntax:

form.alpha(name[, error]);

Arguments:

  1. name - (string) The name of the form element to which the validation should be applied.
  2. error - (string, optional) The error message to be displayed on validation failure. Default message: "This field may contain only letters."

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.alpha('firstName'); //Default error
	form.alpha('lastName', 'Please enter only letters for your last name'); //Custom error
});

VMFormValidator Method: alphanumeric

Validates alphanumeric characters.

Syntax:

form.alphanumeric(name[, error]);

Arguments:

  1. name - (string) The name of the form element to which the validation should be applied.
  2. error - (string, optional) The error message to be displayed on validation failure. Default message: "This field may contain only letters or numbers."

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.alphanumeric('code'); //Default error
	form.alphanumeric('code', 'Code can contain only letters or numbers.'); //Custom error
});

VMFormValidator Method: canadaPostal

Validates Canadian Postal codes.

Syntax:

form.canadaPostal(name[, error]);

Arguments:

  1. name - (string) The name of the form element to which the validation should be applied.
  2. error - (string, optional) The error message to be displayed on validation failure. Default message: "Please enter a valid Canadian Postal Code."

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.canadaPostal('postal'); //Default error
	form.canadaPostal('postal', 'You don't really live in Canada, do you?'); //Custom error
});

See also:

VMFormValidator Method: credit

Validates all major credit card types including Visa, Mastercard, American Express, and Discover.

Syntax:

form.credit(name[, error]);

Arguments:

  1. name - (string) The name of the form element to which the validation should be applied.
  2. error - (string, optional) The error message to be displayed on validation failure. Default message: "Please enter a valid credit card number."

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.credit('credit'); //Default error
	form.credit('credit', 'That must have been your library card number. Try again.'); //Custom error
});

VMFormValidator Method: dateMDY

Validates a date in Month/Day/Year format. Accepts spaces, hyphens, forward slashes, or periods as seperators.

Syntax:

form.dateMDY(name[, error]);

Arguments:

  1. name - (string) The name of the form element to which the validation should be applied.
  2. error - (string, optional) The error message to be displayed on validation failure. Default message: "Please enter a valid date in M/D/Y format."

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.dateMDY('date'); //Default error
	form.dateMDY('date', 'Not a prune. A date.'); //Custom error
});

VMFormValidator Method: dateYMD

Validates a date in Year/Month/Day format. Accepts spaces, hyphens, forward slashes, or periods as seperators.

Syntax:

form.dateYMD(name[, error]);

Arguments:

  1. name - (string) The name of the form element to which the validation should be applied.
  2. error - (string, optional) The error message to be displayed on validation failure. Default message: "Please enter a valid date in Y/M/D format."

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.dateYMD('date'); //Default error
	form.dateYMD('date', 'If I have to pay, it isn't a real date.'); //Custom error
});

VMFormValidator Method: email

Validates most email addresses.

Syntax:

form.email(name[, error]);

Arguments:

  1. name - (string) The name of the form element to which the validation should be applied.
  2. error - (string, optional) The error message to be displayed on validation failure. Default message: "Please enter a valid email address."

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.email('email'); //Default error
	form.email('email', 'Did you want me to guess your email address?.'); //Custom error
});

See also:

VMFormValidator Method: excludes

Will return an error if any of the array values are present.

Syntax:

form.excludes(name, arrayCheck[, error]);

Arguments:

  1. name - (string) The name of the form element to which the validation should be applied.
  2. arrayCheck - (array) Values that should return an error if they are present.
  3. error - (string, optional) The error message to be displayed on validation failure. Default message: "This field cannot contain any of the following values: arrayCheck[]."

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.excludes('spam', ['get rich quick', 'affiliate', 'millions']); //Default error
	form.excludes('spam', ['lottery', 'Nigeria', 'dead relative'], 'So sorry, we already made our millions.'); //Custom error
});

See also:

VMFormValidator Method: imageFile

Validate a file upload input to see if the file is an image.

Syntax:

form.imageFile(name[, error]);

Arguments:

  1. name - (string) The name of the form element to which the validation should be applied.
  2. error - (string, optional) The error message to be displayed on validation failure. Default message: "Please upload a valid image file. Valid files end with one of the following extensions: .jpg, .jpeg, .bmp, .gif, .png."

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.imageFile('photo'); //Default error
	form.imageFile('photo', 'Photos only, please. With a signature, they're only $10 apiece.'); //Custom error
});

VMFormValidator Method: includes

Will return an error if any of the array values are not present.

Syntax:

form.includes(name, arrayCheck[, error]);

Arguments:

  1. name - (string) The name of the form element to which the validation should be applied.
  2. arrayCheck - (array) Values that should return an error if one or more are not present.
  3. error - (string, optional) The error message to be displayed on validation failure. Default message: "This field did not contain any of the following values: arrayCheck[]."

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.includes('comments', ['I love Virtuosi Media', 'thank you', 'biggest fan']); //Default error
	form.includes('comments', ['I love Virtuosi Media', 'thank you', 'biggest fan'], 'Don't you love us?'); //Custom error
});

See also:

VMFormValidator Method: matches

Compares the values of two fields and returns an error if they do not match. Useful for confirming a password.

Syntax:

form.matches(name, compareName[, error]);

Arguments:

  1. name - (string) The name of the form element to which the validation should be applied.
  2. compareName - (string) The name of the form element which name should match.
  3. error - (string, optional) The error message to be displayed on validation failure. Default message: "This field does not match the compareName field."

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.matches('password', 'confirmPassword'); //Default error
	form.matches('password', 'confirmPassword', 'Forget already? Not a good sign...'); //Custom error
});

See also:

VMFormValidator Method: maxLength

Sets a maximum length for a field.

Syntax:

form.maxLength(name, maxLength[, error]);

Arguments:

  1. name - (string) The name of the form element to which the validation should be applied.
  2. maxLength - (integer) The maximum number of characters to be entered into the form element.
  3. error - (string, optional) The error message to be displayed on validation failure. Default message: "This field may contain no more than maxLength characters."

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.maxLength('name', 50); //Default error
	form.maxLength('name', 50, 'Helloooo Hemingway.'); //Custom error
});

See also:

VMFormValidator Method: minLength

Sets a minimum length for a field.

Syntax:

form.minLength(name, minLength[, error]);

Arguments:

  1. name - (string) The name of the form element to which the validation should be applied.
  2. minLength - (integer) The minimum number of characters to be entered into the form element.
  3. error - (string, optional) The error message to be displayed on validation failure. Default message: "This field must contain at least minLength characters."

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.minLength('name', 4); //Default error
	form.minLength('name', 4, "Stingy, aren't we? Type at least four characters, please."); //Custom error
});

See also:

VMFormValidator Method: noMatches

Compares the values of two fields and returns an error if they match. Useful making sure a password doesn't match a username.

Syntax:

form.noMatches(name, compareName[, error]);

Arguments:

  1. name - (string) The name of the form element to which the validation should be applied.
  2. compareName - (string) The name of the form element which name cannot match.
  3. error - (string, optional) The error message to be displayed on validation failure. Default message: "This field cannot match the compareName field."

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.noMatches('password', 'username'); //Default error
	form.noMatches('password', 'username', "That's like asking to be hacked."); //Custom error
});

See also:

VMFormValidator Method: numeric

Validate if a form element's value is numeric.

Syntax:

form.numeric(name[, error]);

Arguments:

  1. name - (string) The name of the form element to which the validation should be applied.
  2. error - (string, optional) The error message to be displayed on validation failure. Default message: "This field may contain only numbers."

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.numeric('page'); //Default error
	form.numeric('page', "I can always count on you to type something you're not supposed to. Please enter only numbers."); //Custom error
});

Notes:

See also:

VMFormValidator Method: password

Validates a password of at least one lowercase letter, one uppercase letter, and one number. The password must be at least 6 characters long.

Syntax:

form.password(name[, error]);

Arguments:

  1. name - (string) The name of the form element to which the validation should be applied.
  2. error - (string, optional) The error message to be displayed on validation failure. Default message: "Your password must contain one lowercase letter, one uppercase letter, one number, and be at least 6 characters long."

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.password('password'); //Default error
	form.password('password', "That's probably your cat's name, isn't it? Try something a little harder to crack."); //Custom error
});

VMFormValidator Method: phone

Validates a North American phone number, with the area code required. Allows for optional spaces, hyphens, or periods as separators and parentheses for the area code. A leading one or zero is also optional.

Syntax:

form.phone(name[, error]);

Arguments:

  1. name - (string) The name of the form element to which the validation should be applied.
  2. error - (string, optional) The error message to be displayed on validation failure. Default message: "Please enter a valid phone number including area code."

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.phone('phone'); //Default error
	form.phone('phone', "Please? We promise we won't call."); //Custom error
});

VMFormValidator Method: range

Sets a minimum length for a field.

Syntax:

form.range(name, minLength, maxLength[, error]);

Arguments:

  1. name - (string) The name of the form element to which the validation should be applied.
  2. minLength - (integer) The minimum number of characters to be entered into the form element.
  3. maxLength - (integer) The maximum number of characters to be entered into the form element.
  4. error - (string, optional) The error message to be displayed on validation failure. Default message: "This field must contain at least minLength and no more than maxLength characters."

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.range('password', 4, 10); //Default error
	form.range('password', 4, 10, "Let's compromise. Not too long. Not too short."); //Custom error
});

See also:

VMFormValidator Method: required

Makes any form element required.

Syntax:

form.required(name[, error]);

Arguments:

  1. name - (string) The name of the form element to which the validation should be applied.
  2. error - (string, optional) The error message to be displayed on validation failure. Default message: "This field is required."

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.required('creditCard'); //Default error
	form.required('creditCard', "Payment is required."); //Custom error
});

Notes:

VMFormValidator Method: swearFilter

Triggers an error if a common swear word is present in a form element.

Syntax:

form.swearFilter(name[, error]);

Arguments:

  1. name - (string) The name of the form element to which the validation should be applied.
  2. error - (string, optional) The error message to be displayed on validation failure. Default message: "Please refrain from using profanity."

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.swearFilter('comments'); //Default error
	form.swearFilter('comments', "That wasn't a very nice thing to say."); //Custom error
});

Notes:

See also:

VMFormValidator Method: url

Validates most URLs.

Syntax:

form.url(name[, error]);

Arguments:

  1. name - (string) The name of the form element to which the validation should be applied.
  2. error - (string, optional) The error message to be displayed on validation failure. Default message: "Please enter a valid URL."

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.url('website'); //Default error
	form.url('website', "What part of 404 don't you understand?"); //Custom error
});

See also:

VMFormValidator Method: usZip

Validates US ZIP codes. The four digit ZIP code extension is optional.

Syntax:

form.usZip(name[, error]);

Arguments:

  1. name - (string) The name of the form element to which the validation should be applied.
  2. error - (string, optional) The error message to be displayed on validation failure. Default message: "Please enter a valid US ZIP Code."

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.usZip('zip'); //Default error
	form.usZip('zip', 'Bonus points if you can enter a correct ZIP code AND tell me what ZIP stands for.'); //Custom error
});

See also:

VMFormValidator Method: validateRegEx

Validates a custom regular expression.

Syntax:

form.validateRegEx(regex, name, error);

Arguments:

  1. regex - (string) A regex to evaluated.
  2. name - (string) The name of the form element to which the validation should be applied.
  3. error - (string) The error message to be displayed on validation failure. There is no default message.

Example:

window.addEvent('domready', function(){
	var form = new VMFormValidator('exampleForm');
	form.validateRegEx('mootools', 'favorite', "You must type 'MooTools.'"); 
});

Further JavaScript Regular Expression Resources: