Validating Forms in JQuery - J Query

Most registration forms require input of email address, a password (two times), a username and some other information, like a birth date. This applies to email services, web shops, or forums.
It’s easy to imagine John Doe, who wants to buy a new monitor at some web shop where the registration also requires the input of a captcha(a barely legible group of random characters to tell the difference between a human and a bot). He fills out the complete form, which takes some time, and then submits the form. After about five seconds, the form is displayed again, with some error message at the top: he forgot to fill out the street field. He fixes that and submits again. Another five seconds pass: now he missed the password and captch a field! Huh? He did fill those in, but he had to fill them in again after the failed first attempt.
Such late feedback can be very frustrating and can ruin an experience that was otherwise good, especially when security concerns limit functionality—here causing the empty password and captch a fields.


One way to improve the situation is to add client-side validation. The basic idea is to give the user feedback as early as possible, without annoying him. It should n’t be possible to submit an invalid form, avoiding the issue of filling in passwords or captch as again.
It also makes sense to highlight errors on fields after they are filled in, as in the case of an invalid email address like Highlighting fields as wrong does n’t help when it happens before the user even has the chance to fill out a field correctly: to display “too short” on a field that requires at least two characters, after the user types the first character, is n’t helping at all.
A plugin covering these requirements quite well is the validation plugin.
To get started, download the plugin, extract the files, and copy jquery.validate.js to your project. The following example shows a comment form with fields for name,email, URL, and actual comment. A call to the plugin method validate() sets up the validation for the form. Validation rules are specified inline using classes and attributes:

Any field with the class required is checked to have any content at all. Other methods in this example include the following:


Checks that the field contains a valid email address


Checks that the field contains a valid URL


Checks that the field contains at least x characters; here x is specified via an attribute: minlength="2"


The validation plugin promotes one specific approach to client-side validation: perform as much work as possible in the browser, and ask the server for help only in special cases, which are covered by the remote method, for example, to check whether a username is still available.
A different approach would avoid replicating validation rules and methods on both the client and server sides, instead sending the whole form via Ajax to the server, usually on submit of the form. It could then use the same logic on the server side that is in place already. The drawback is that user feedback is slower, because it is impractical to send a request for every keypress. It’s also not very likely that the server validation was written with Ajax validation in mind, making it impractical to reuse it. In that case, you’d have to plan up front to use it that way.
The validation plugin can be added to a form later, and apart from remote validation,there is no need to adapt the application in any way. This makes it useful for a simple comment form on a blog, as well as more complex forms on some intranet application and anything in between.
The most important building blocks for the plugin are rules and methods. Methods contain validation logic, like the email method that uses a regular expression to determine whether a value is a valid email address. Rules wire input fields together with methods, where a single rule is a pair of an input field and a method. The email field then has one rule for making it required and one for making it an email address.


The plugin has about 19 built-in methods. The essential method is required—when specified, the field has to be filled out. When left out, most other methods will be ignored on an empty field. The only exception to that is the equal To method, which checks that the content of a field is exactly the same as some other field, which even applies for an empty field. The rule itself is most commonly used for “Confirm password”fields.
The email, url, date, dateISO, dateDE, number, numberDE, digits, and creditcard methods all check for certain data types, with simple variations for different locales. For example, number requires a U.S. number format like 1,000.00, and numberD Erequires the German number format 1.000,00.
The min and max and range methods check the value of a number, while minlength, maxlength, and range length check the number of characters.
In case of a select input or checkboxes, min, max, and range validate the number of selected options or checked checkboxes.
In case of file inputs, the accept method comes in handy and checks the file extension,by default looking for .gif, .png, .jpg, or .jpeg.
The remote method is the only method that delegates the actual validation logic elsewhere,to the server side. It gets a URL as the parameter, pointing at some server-side resource. This could be a script that does a database query, for example, for checking if a username is already taken or if a specified email address is already registered.

Custom methods are a good way to extend the plugin with application specific requirements. You may have a form where users enter URLs that have to start with a certain corporate domain. A custom method could encapsulate the necessary validation:

The first argument to jQuery.validator.addMethod is the name of the custom method,and it must be a valid JavaScript identifier. The second argument is a function that implements the actual validation. If it returns true, the input is considered valid. It uses this . optional (element) to determine whether that input has no value and should therefore be skipped—all default methods use the same call. The third argument specifies the default message for the new method.
Writing methods that accept a parameter works very similarly:

In this case, the default message is specified with the help of jQuery. format, a templating helper the plugin provides. The indexed curly-braced placeholders are replaced with the actual parameters when the validation is run.
Custom methods can also reuse existing methods, which is useful to specify different default messages for a single method. In this example, the required method is aliased to customer Required with a different default message:

A collection of ready-to-use custom methods are bundled with the plugin in additional Methods. js.


There are four distinct ways to specify rules: two in code and two inline as metadata.The previous example uses classes and attributes as metadata, which the plugin supports by default. When the metadata plugin is available, rules can be embedded in various ways, for example, inside the class attribute:

Here the class contains JavaScript literals inside curly braces, which is very similar in syntax to specifying rules in code via the rules option:

The object keys like name, email, url, and comment always refer to the name of the element, not the ID.
Note the shortcuts used for url and comment, where only a single rule is necessary. This is n’t available when specifying rules with parameters, like min length.
Some rules need to be added later, which is possible using the fourth way, the rulesplugin method:

That click event code removes the required rule from the password, tries to submit the form (triggering the validation), and adds the rule back. That way, the username field is still being validated, and if the validation fails, the password field will be required again (in case of a normal form submit).
Often the validation behavior of a field depends on some more factors than just a link being clicked. Those can be handled using parameters for the required method. The parameter can be a selector or a callback. The selector is useful when the dependency can be written in a simple expression. An email field may be required only when the newsletter checkbox is selected:

The previous example used the :blank expression to select an element only when it has no value at all or only white space. The plugin also provides the :filled expression, the inversion of :blank. jQuery itself provides :checked, and the validation plugin adds the inversion :unchecked. Both are useful when specifying dependencies on radio buttons or check boxes.
While you could use the :not expression to inverse :filled or :checked, :blank and :unchecked make the selector more readable and therefore easier to understand ata glance.

Error messages

Similar to rules, there are a few ways to specify messages, both in code and inline. Inline messages are read from the title attribute:

A valid email address is

That will produce a single error message for each rule. An alternative inline approach is to use the metadata plugin

With this approach, you can specify a message for each rule, which is also possible when using the messages option:

Again, the keys—here, email—refer to the name of the input, not the ID, just the same as specifying rules.For more dynamic scenarios, the rules plugin method can be used:

If you use some of the alternatives to the title attribute while using a regular title, you can suppress the plugin from checking the attribute for messages:

The default messages are in English (with the exception of dateDEandnumberDE). In addition, the plugin provides (at the time of this writing) 17 localizations.
Usage is plain and simple: just copy the messages_xx.js file you need to your project,and include it after the validation plugin. For example, here’s the code for the Swedish localization:

With that in place, instead of “Please enter a valid email address.” you’ll get “Ange en korrekt e-postadress.”

By default error messages are inserted into the DOM next to the element that they are referring to. An error message is inserted as a label element, with the for attribute set to the id of the validated element. Using a label with the for attribute leverages the browser feature where a click on the label gives focus to the input field.So by default, the user can click the error message to give the invalid field focus.

If you need a different element type, use the error Element option:

The plugin will still use the for attribute then, but the auto linking the browser provides won’t work.
If you want to customize the position where error messages are inserted, the error Placement option is useful. We may have a form that uses a table for layout, where the first column contains the regular label, the second the input, and the third the messages:

Another common requirement is to display a general message above the form. The error Container option helps with that:

In this example, an element with the ID messageBox1 would be shown when the form is invalid and would be hidden when valid.This can also be combined with the error Label Container option. When specified, errorlabels are n’t placed next to their input elements but instead added to a single element above or below the form. Combined with the error Container and wrapper options,messages are added to a list of errors above the form:

Handling the submit

Once the form is valid, it has to be submitted. By default that just works as any other form submit. To submit the form via Ajax, the submit Handler option can be used, together with the form plugin

The in valid Handler callback is useful for running code on an invalid submit. The following example displays a summary of the missing fields:

The Marke to demo shows this behavior in action (


So, when does it make sense to not use the plugin and write a validation solution from scratch? There are certain limitations: forms where groups of inputs, like checkboxes,have different name attributes are hard to validate as a group. Lists of inputs that all have the same name can’t be validated, because each individual input needs its own unique name. If you stick with the naming convention of unique names for individual inputs and one name for groups of checkboxes or radio buttons, the plugin works fine.
If your application has only a login form, the plugin is probably overkill, and it would be difficult to justify the file size; however, if you use the plugin somewhere else on asite, it can be used for the login form as well.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

J Query Topics