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.
VMFormValidator is released under the open-source MIT License.
VMFormValidator requires the MooTools JavaScript framework. Specifically, it requires the complete MooTools Core (but not MooTools More) file.
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!
This class is for validating forms.
VMFormValidator is completely unobtrusive and requires no changes to existing markup, provided the form has an id and uses labels.
var form = new VMFormValidator(formId[, options]);
window.addEvent('domready', function(){ var form = new VMFormValidator('exampleForm'); });
Adds a custom function to the onBlur and onSubmit events, to be run with the rest of the validations.
form.addFunction(name, customFunction);
var custom_function = function(){ alert('This is a custom function'); } window.addEvent('domready', function(){ var form = new VMFormValidator('exampleForm'); form.addFunction('firstName', 'custom_function()'); });
Validates alphabetic characters.
form.alpha(name[, error]);
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 });
Validates alphanumeric characters.
form.alphanumeric(name[, error]);
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 });
Validates Canadian Postal codes.
form.canadaPostal(name[, error]);
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 });
Validates all major credit card types including Visa, Mastercard, American Express, and Discover.
form.credit(name[, error]);
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 });
Validates a date in Month/Day/Year format. Accepts spaces, hyphens, forward slashes, or periods as seperators.
form.dateMDY(name[, error]);
window.addEvent('domready', function(){ var form = new VMFormValidator('exampleForm'); form.dateMDY('date'); //Default error form.dateMDY('date', 'Not a prune. A date.'); //Custom error });
Validates a date in Year/Month/Day format. Accepts spaces, hyphens, forward slashes, or periods as seperators.
form.dateYMD(name[, error]);
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 });
Validates most email addresses.
form.email(name[, error]);
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 });
Will return an error if any of the array values are present.
form.excludes(name, arrayCheck[, error]);
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 });
Validate a file upload input to see if the file is an image.
form.imageFile(name[, error]);
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 });
Will return an error if any of the array values are not present.
form.includes(name, arrayCheck[, error]);
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 });
Compares the values of two fields and returns an error if they do not match. Useful for confirming a password.
form.matches(name, compareName[, error]);
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 });
Sets a maximum length for a field.
form.maxLength(name, maxLength[, error]);
window.addEvent('domready', function(){ var form = new VMFormValidator('exampleForm'); form.maxLength('name', 50); //Default error form.maxLength('name', 50, 'Helloooo Hemingway.'); //Custom error });
Sets a minimum length for a field.
form.minLength(name, minLength[, error]);
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 });
Compares the values of two fields and returns an error if they match. Useful making sure a password doesn't match a username.
form.noMatches(name, compareName[, error]);
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 });
Validate if a form element's value is numeric.
form.numeric(name[, error]);
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 });
Validates a password of at least one lowercase letter, one uppercase letter, and one number. The password must be at least 6 characters long.
form.password(name[, error]);
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 });
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.
form.phone(name[, error]);
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 });
Sets a minimum length for a field.
form.range(name, minLength, maxLength[, error]);
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 });
Makes any form element required.
form.required(name[, error]);
window.addEvent('domready', function(){ var form = new VMFormValidator('exampleForm'); form.required('creditCard'); //Default error form.required('creditCard', "Payment is required."); //Custom error });
Triggers an error if a common swear word is present in a form element.
form.swearFilter(name[, error]);
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 });
Validates most URLs.
form.url(name[, error]);
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 });
Validates US ZIP codes. The four digit ZIP code extension is optional.
form.usZip(name[, error]);
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 });
Validates a custom regular expression.
form.validateRegEx(regex, name, error);
window.addEvent('domready', function(){ var form = new VMFormValidator('exampleForm'); form.validateRegEx('mootools', 'favorite', "You must type 'MooTools.'"); });