How to Validate Forms Using jQuery
Writing your own form validation code doesn't have to be a scary or time-consuming process. jQuery's Validation Plugin makes form validation easy and straightforward.
To get started, all you need to do is link to the plugin files (files are also available for download if you'd prefer to host them locally) along with your standard jQuery library link.
[javascript]
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js"></script>
[/javascript]
From there, you can start coding. Here's what the validation code might look like if you have a form with 4 different input fields (First Name, Last Name, Email, Password) you'd like to validate:
[javascript]
//we're going to run form validation on the #validate-form element
$("#validate-form").validate({
//specify the validation rules
rules: {
firstname: "required",
lastname: "required",
email: {
required: true,
email: true //email is required AND must be in the form of a valid email address
},
password: {
required: true,
minlength: 6
}
},
//specify validation error messages
messages: {
firstname: "First Name field cannot be blank!",
lastname: "Last Name field cannot be blank!",
password: {
required: "Password field cannot be blank!",
minlength: "Your password must be at least 6 characters long"
},
email: "Please enter a valid email address"
},
submitHandler: function(form){
form.submit();
}
});
[/javascript]
It's important to makes sure that the names of your input fields match your jQuery code, so for example, the HTML for the First Name input field should look something like this:
[html]
<input type="text" name="firstname">
[/html]
Additionally, the id of your form needs to match the id called to validate in the first line of the above jQuery code, so in this case, the form's id would need to be #validate-form in order for this code to work.
That's all it takes to create some basic form validation in only a few minutes! Read through the jQuery Validation Plugin's documentation to learn even more about how to utilize this helpful plugin.