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 will learn how to use a jQuery plugin to add 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 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 will 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 will also need to add a link to the jQuery library.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
Once you have 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 will be validating using the jQuery validate plugin.
<form id="basic-form" action="" method="post"> <p> <label for="name">Name <span>(required, at least 3 characters)</span></label> <input id="name" name="name" minlength="3" type="text" required> </p> <p> <label for="email">E-Mail <span>(required)</span></label> <input id="email" type="email" name="email" required> </p> <p> <input class="submit" type="submit" value="SUBMIT"> </p> </form>
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 will 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:
$(document).ready(function() { $("#basic-form").validate(); });
This is based on the assumption that you have 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 are 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 will 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 is 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 the 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()
. All form elements with that particular selector will be ignored by the plugin while validating 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 are 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.
$(document).ready(function() { $("#basic-form").validate({ rules: { name : { required: true, minlength: 3 }, age: { required: true, number: true, min: 18 }, email: { required: true, email: true }, weight: { required: { depends: function(elem) { return $("#age").val() > 50 } }, number: true, min: 0 } } }); });
In the above code snippet, the keys name
, age
, email
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.
messages : { name: { minlength: "Name should be at least 3 characters" }, age: { required: "Please enter your age", number: "Please enter your age as a numerical value", min: "You must be at least 18 years old" }, email: { email: "The email should be in the format: abc@domain.tld" }, weight: { required: "People with age over 50 have to enter their weight", number: "Please enter your weight as a numerical value" } }
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 that you will 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 will 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 specifcially 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 in preventing some unwanted clashes due to reusing the same class name. By default, the class error
is assigned to every invalid input element and label. The class valid
is assigned to every valid input element.
It is important to remember that setting errorClass
to something like fail-alert
will remove the class error
from the invalid elements. You will have to use errorClass: "error fail-alert"
to assign multiple classes to 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.
$(document).ready(function() { $("#basic-form").validate({ errorClass: "error fail-alert", validClass: "valid success-alert", // ... More validation code from previous example
Here is the CSS that we will use to change the appearance of error messages:
label.error.fail-alert { border: 2px solid red; border-radius: 4px; line-height: 1; padding: 2px 0 6px 6px; background: #ffe6eb; } input.valid.success-alert { border: 2px solid #4CAF50; color: green; }
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 onfocusout
, onkeyup
, 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 are 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 change the placement of error messages or group them all together.
Final Thoughts
In this tutorial, we learned how to take our form validation to the next level using a jQuery plugin. Using 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 would 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 will 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!
-
HTML5Form Input Validation Using Only HTML5 and Regex
-
Web DevelopmentSubmit a Form Without Page Refresh Using jQuery
-
PHPCreate a Contact Form in PHP
-
PHPComparing the 5 Best PHP Form Builders (And 4 Free Scripts)
-
JavaScriptBest JavaScript Forms of 2019
No comments:
Post a Comment