7 days of WordPress plugins, themes & templates - for free!* Unlimited asset downloads! Start 7-Day Free Trial
  1. Code
  2. JavaScript

Easy Form Validation With jQuery

Read Time: 11 mins

In our previous tutorial, we discussed how to implement basic form validation using some input attributes in HTML5 and a little regex.

In this tutorial, you'll learn how to use a jQuery plugin to add simple form validation to your website.

Using a jQuery plugin to validate forms serves a lot of purposes. It gives you additional abilities like easily displaying custom error messages and adding conditional logic to jQuery form validation. A validation library can also help you add validation to your HTML forms with minimal or no changes to the markup. The conditions for validity can also be added, removed, or modified at any time with ease.

Getting Started

We'll use the jQuery Validation Plugin in this tutorial. The plugin offers a lot of features and also helps you define your own validation logic.

Before we can start using the plugin in our fields, we have to include the necessary files in our project. There are two different files to include. The first is the core file, which includes the core features of the plugin, including everything from different validation methods to some custom selectors. The second file contains additional methods to validate inputs like credit card numbers and US-based phone numbers.

You can add these files to your projects via package managers like Bower or NPM. You can also just directly get a CDN link to the files and add them to a script tag on your webpage. Since this is a jQuery-based plugin, you'll also need to add a link to the jQuery library.

Once you've added these files, you can start validating any form with the validate method.

Validating Your First Form

You can start using this plugin without making any significant changes to your markup. The only thing that you might have to change is to add an id or class to the form you want to validate if it doesn't have one already.

Here is the markup of a basic form that we'll be validating using the jQuery validate plugin.

We are using the same attributes that we used in our previous HTML5-based form validation tutorial. The form will still do the validation without us adding any JavaScript. However, using the plugin for validation will let us show the error messages right below the invalid input field. We'll also be able to style the errors however we want.

To start validating the form with this plugin, simply add the following JavaScript code on the webpage:

This is based on the assumption that you've already added the required JavaScript files. Adding those lines of JavaScript will make sure that your form is properly validated and shows all the error messages. Here is a working demo.

The library tries to be as user-friendly as possible by only showing error messages when they're necessary. For example, if you tab through the name and email fields without actually entering any information, you won't get any error messages. However, if you try to move to the email field after only entering one character in the name field, you'll get an error message about entering at least three characters.

The error messages are injected into the DOM using the label element. All of them have an error class, so it's easy to apply your own styling, as we did in our example. The same is true for invalid inputs, which also get an error class added to them.

Options for the validate() Method

In our previous example, we simply called the validate() method without passing any options to it. However, we can also pass an object to this method along with many options inside that object. The value of these options will determine how the form plugin handles validation, errors, etc.

If you want this plugin to ignore some elements during the validation process, you can do so easily by passing a class or selector to ignore(). The plugin will ignore all form elements with that particular selector when it validates the input.

Add Validation Rules for Input Fields

You can also pass some rules to the validate() method in order to determine how the input values are validated. The value of the rules parameter should be an object with key-value pairs. The key in each case is the name of the element that we want to validate. The value of that key is an object which contains a set of rules which will be used for validation.

You can also add conditional logic to the different fields that you're validating by using the depends keyword and passing a callback function to it which returns either true or false. Here is an example which uses simple rules to define how the input is validated.

In the above code snippet, the keys nameageemail and weight are simply the names of input elements. Each key has an object as its value, and the key-value pairs in the object determine how an input field will be validated.

These validation options are similar to the attributes that you can add in the markup of a form. For example, setting required to true will make the element required for form submission. Setting minlength to a value like 3 will force users to enter at least 3 characters in the text input. There are a few other built-in validation methods which are briefly described on the documentation page.

One thing that you should note in the above code is the use of depends to conditionally make the weight a required field if the age is over 50. This is done by returning true in the callback function if the value entered in the age input field is over 50.

Create Your Own Error Messages

This plugin also allows you to set error messages for different validation rules in a form. You begin by setting the value of the messages key to an object with key-value pairs for the input fields and the corresponding error messages.

Here is an example which will display custom error messages for each input field.

Just like rules, messages rely on the name of the input fields. Each of these input fields will accept an object with key-value pairs as its value. The key in each case is the validation rule which has to be followed. The value is simply the error message that you want to display if a particular rule is violated.

For instance, the age input field will trigger the required error message if left blank. However, it will trigger the number error if you enter anything else besides a number in the input field.

One thing you'll notice is that the plugin will show a generic error message for validation rules where you haven't supplied a custom error message. Try filling out different values in the following demo, and you'll see that the custom and generic error messages show up as expected.

Customizing the Appearance of Error Messages

There are times when you might want to add your own classes to valid and invalid input in order to target them more specifically or for better integration with an existing theme.

You can change the classes which are added to valid or invalid input elements using the errorClass and validClass keys. This can help prevent some unwanted clashes due to reusing the same class name. By default, the error class is assigned to every invalid input element and label. The valid class is assigned to every valid input element.

It's important to remember that setting errorClass to something like fail-alert will remove the error class from the invalid elements. You'll have to use errorClass: "error fail-alert" to assign multiple classes to the same element. The same goes for validClass.

There are no additional labels added to the form when users enter a valid input. So the classes from validClass are assigned to the valid input element.

The following code snippet builds upon the previous example to add custom CSS classes and styling to invalid and valid elements.

The only additional JavaScript code is used to assign the classes.

Here is the CSS that we'll use to change the appearance of error messages:

In addition to customizing the error messages, we are also adding our own styling to valid input elements. Here is a CodePen demo to show us the final result.

More Options to Change the Plugin Behavior

You can prevent the plugin from validating input fields on key up, click, and other such events by setting the value of onfocusoutonkeyup, or onclick to false. Keep in mind that boolean true is not a valid value for these keys. This basically means that if you want the plugin to validate or lose focus on a key up event, just leave these options untouched.

You also have the option to change the element in which the error appears. By default, the plugin uses the label element to show all error messages, but you can change it to em or any other element using the errorElement key. The error element itself can then be wrapped in another HTML element using the wrapper key.

These are some of the most common options that you're likely to use when validating forms. However, there are some other validation options that might come in handy if you want to do something like changing the placement of error messages or grouping them all together.

jQuery Form Validation, JavaScript, and jQuery Forms Found on CodeCanyon

Learning how to do simple form validation by yourself is a great skill to have. But you can get even deeper with these useful jQuery and JavaScript form downloads from CodeCanyon:

1. jQuery Step Wizard With Step Form Builder: Timon Step Form

Timon Step Wizard JavaScript FormTimon Step Wizard JavaScript FormTimon Step Wizard JavaScript Form

If you want to build a multi-step form, the Timon Step Form download is right for you. It features multiple form elements and transition effects that you can use to customize your work. Timon also has a drag-and-drop builder, meaning you can build your form without needing any coding knowledge. It also has jQuery form validation. 

2. Just Forms Advanced

Just Forms Advanced JavaScript FormJust Forms Advanced JavaScript FormJust Forms Advanced JavaScript Form

Reading the name of this purchase will let you know exactly what you're getting here. But there's more to these forms than meets the eye. The more than 110 included forms are ready for use, or you can use the framework to make a unique form for yourself.

3. Sky Forms

Sky Forms JavaScript FormSky Forms JavaScript FormSky Forms JavaScript Form

We round out our list with the highly customizable Sky Forms. It comes with modern elements and multiple color schemes. There are also six designed states, including hover, focus, and more. On top of these features and the cross-browser compatibility, there are over 300 vector icons in Sky Forms.

Final Thoughts

In this tutorial, we learned how to take our form validation to the next level using a jQuery plugin. Using simple JavaScript form validation gives us a lot of additional control over basic HTML validation. For instance, you can easily control how and when different error messages appear when an input is filled with invalid values.

Similarly, you can also specify if the plugin should skip validation for some particular elements. I'd strongly recommend that you read the documentation of this plugin and some best practices on how to use it properly.

In our next tutorial, you'll learn about some more JavaScript-based tools and plugins to help you easily create and validate forms.

And while you're here, check out some of our other posts on JavaScript forms and form validation!

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Scroll to top
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.