Keep your forms validating properly with jQuery validator.
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:
In order to start using our plugin, we need to put the code below:
Here's our complete jQuery code:
Finally, once our form is working, we add styling to our it:
There we have it. You can click on the form fields below, type information and see how the validation works.