How to Use jQuery Validator for Your Form Validation


Keep your forms validating properly with jQuery validator.

How to Use jQuery Validator for Your Form Validation

Adding validation to your forms with jQuery gives you a lot of flexibility as you can add more rules and conditions to your validation and you can customize the error messages. There's even an easier way to add validation using the jQuery validation plugin and in this tutorial, we will use this plugin.

The first thing we need to do is add the necessary jQuery files to out HTML file. The first one is the standard jQuery library and the second one is the jQuery plugin. You can either download the jQuery plugin file, place it under a folder and call it in your HTML file or you can put a CDN link to the file then use the script tag to include your jQuery code. In this example, we're using a CDN link:

Once we add the files, we can start using the validation plugin by invoking the .validate method. In this tutorial, we are using Bootstrap and the good thing about using the jQuery validation plugin is we don't have to change out mark-up to make the plugin work. In our markup, all we need to do is add an id to our form tag and all the input fields we have such as "first name", "last name", "e-mail" etc. because inside our jQuery code, we'll need to specify these input fields by their id names. Here's our HTML form:

Under each input field, we put a label tag for the error messages. Just like the input fields, we give these labels an id and a classname to style them in our CSS file. 

Here's our full HTML file:

HTML

In order to start using our plugin, we need to put the code below:

The $(document ).ready() method will run once the page is loaded and is ready to execute Javascript code. After the $(document ).ready() method, we added a method by using  jQuery.validator.addMethod to check if the e-mail is valid by checking its format using regular expression. Next, we use the rules parameter to specify validation rules. 

Here's our complete jQuery code:

jQuery

Finally, once our form is working, we add styling to our it:

CSS

There we have it. You can click on the form fields below, type information and see how the validation works.
 

Author

Paris Tuzun
Contributions Editor here at Solodev. Want to be featured on the Solodev Blog? Get in touch.
Follow me on Twitter

Get started today

Join people and businesses across the globe that trust Solodev.

We never share your information with anyone. Learn more

We use cookies to provide and improve our services. By using our site, you consent to cookies.