Posted in JavaScript & Web Development.
Form validation is one of the most elementary practical uses of JavaScript. It is a standard topic in introductory JavaScript courses and is handled by numerous libraries. This entry seeks to explain how to use and extend the jQuery form validation plugin. You’ll need a basic working knowledge of the plugin to benefit from this entry. Learn the basics of the jQuery form validation plugin if you haven’t done so already.
Building Blocks of Form Validation
The jQuery form validation plugin is made up of three basic building blocks: form elements, rules, and methods. Together these are processed by the plugin to determine a form’s validity on a field-by-field basis. If a single field is invalid, the form will not submit. The individual form elements, rules, and methods are loosely-coupled and extensible.
Form Elements
Form elements are just that. They are fields in a form that require validation. Using the plugin, form validation is possible on text inputs, checkboxes, radio buttons, and select boxes. The elements may live within a label, or outside of it provided the label contains a for attribute. This provides plenty of flexibility when structuring your form markup.
You setup a field for validation by applying one or more class names to the element, each of which is associated with a rule of the same name: <input class="phone" name="phone" type="text" />.
Rules
Validation rules associate form elements with a validation method (or methods). They are the glue that holds elements and methods together. Rules may be singular: a rule associates an element with a single validation method, or compound: a rule associates an element with multiple validation methods. Rules are easy to build and may be reused by any number of form elements.
Form rules can easily be created via the .addClassRules() method.
$.validator.addClassRules({
password: {
required: true,
minLength: 5
}
});
Methods
Validation methods provide the behind-the-scenes functionality of form validation. A form validation method accepts a value argument and returns a boolean: true for valid and false for invalid. Often, the validation method simply tests a field value against a regular expression. In other cases, advanced dependency checking is performed (for instance, a second password field depends on the first password field for its own validity).
Validation methods can be added via the .addMethod() method.
$.validator.addMethod('postalCode', function (value) {
return /^((\d{5}-\d{4})|(\d{5})|([A-Z]\d[A-Z]\s\d[A-Z]\d))$/.test(value);
}, 'Please enter a valid US or Canadian postal code.');
View working with the jQuery form validation plugin in the lab →.
Creating Compound Rules
In their most basic form, validation rules associate one form element with one validation method. It is possible to associate multiple rules with one element by applying additional rule class names to the element. For instance, a field labeled “phone” may be required, a number, and within the length range of 7 to 10 characters.
<input class="{required: true, number: true, rangeLength: [7, 10]}" name="phone" type="text" />
As the complexity of an element’s validation grows, so too would the number of classes on the element. There is an easier way. It’s possible to create a compound rule: a rule with one name that is composed of multiple validation methods. This is easy with the plugin’s built-in .addClassRules() method.
<input class="phone" name="phone" type="text" />
$.validator.addClassRules({
phone: {
required: true,
number: true,
rangeLength: [7, 10]
}
});
But there is a flaw in this compound rule. Although it does a good job in theory, it won’t handle most real-world phone numbers. Why not? Most human-formatted phone numbers contain spaces, dashes, dots, or parentheses. The rule above can’t account for those characters and invalidates all non-number values.
Custom Validation Methods
Validation methods are at the heart of the plugin. Methods accept as a parameter a value and must return true or false (valid or invalid, respectively). Often they are simple regular expression tests, such as this phone number method. Since they are functions, they can do more complex validation, such as the field-dependent testing of the built-in equalTo method.
$.validator.addMethod('phone', function (value) {
return /^[01]?[- .]?\(?[2-9]\d{2}\)?[- .]?\d{3}[- .]?\d{4}$/.test(value);
}, 'Please enter a valid US or Canadian phone number.');
Arguments & Validation Methods
In previous code sample, we saw values passed into a rule. This has the effect of bounding the validation method in some way. A rule’s value becomes the associated validation method’s arguments. A validation method is called with those arguments via a third parameter.
$.validator.addMethod('isLongerThan', function (value, element, params) {
return (value.length > params[0]);
}, 'Please enter a valid US or Canadian phone number.');
Instead of rewriting validation methods for minor differences, methods can be bound by an argument (or series of arguments). This comes in handy especially for checking the length of field values. For instance, it makes more sense to write a generic maxLength function than an inflexible isShorterThan5Characters function.
A Solid Foundation
My impression is that this plugin is a solid foundation for building up custom form validation. It is relatively painless to create new validation rules and methods, and applying them is a snap. In fact, I already use the form validation plugin on the contact page.
Further Reading
The validation plugin is comprehensive. However, this entry is by no means an exhaustive account of its abilities. There are resources that can help you learn more about it.