Jquery Validation Tutorial Topics
- Introduction To Form Validation Techniques
- Submit and Validate Forms In Jquery
- Validating Form Input Controls
- Handling Error Messages On Form Submission
- Highlighting Form Fields
- Using Button as a Submit Button
- Using Image as a Submit Button
- Email Validation Using Jquery
- Textbox Length Validation
- Textarea Length Validation
- Password Field Validation
- Password Strength Validation – Text
- Password Strength Validation – Graphical
- Block Content Pasting On Text Boxes
- Submit Single Form To Multiple Locations
Introduction To Form Validation Techniques
Used to provide quick responses to enhance user experience. This is optional.
Cannot do database related validations.
This is mandatory and you should not avoid this validation.
Can do database related validations.
In this tutorial I am going to explain how to master client side validations using jquery library. Before we start the tutorial it is important to know why client side validations are required. So lets have a look at the points.
- When the user comes to a page where he is requested to fill a form, enter data and submit to the server, it is important to guide the user on the data required for the form before he submits the form.
- When the user enters the data requested, it’s important to notify whether the data entered can be accepted or not in real time. (Username availability checks,Email Exist checks)
- Once the form is submitted we have to check whether the request is successful or not. If the data cannot be accepted we need to show the errors.
- Validating input field data.
- Restricting input field data.
- Checking input data with server database.
So considering all points mentioned above, let’s start coding some example form validations and form handling techniques.
Submit and Validate Forms In Jquery
2. Validating the form field data according to the requirements.
3. Submitting form to the server or prevent submission depending on the output of validation function.
Here is a simple example for form submission process .
Using Jquery
<script type='text/javascript'>
$('#targets').submit(function() {
var error=1;
if(error){
alert("Error Occured.Cannot Submit the Form");
return false;
}else{
return true;
}
});
</script>
<form id='targets' action='http://www.innovativephp.com' method='post' >
<input type='text' name='test_field' id='test_field' />
<input type='submit' value='Save' />
</form>
Try Demo
Using Javascript
<script type='text/javascript'>
function validateForm(){
var error = 1;
if(error){
alert("Error Occured.Cannot Submit the Form");
return false;
}else{
return true;
}
}
</script>
<form name='target_form' onsubmit='validateForm();' action='http://www.innovativephp.com' method='post' >
<input type='text' name='test_field' id='test_field' />
<input type='submit' value='Save' />
</form>
In both of the examples we call a javascript function in onsubmit event. Once the input fields are validated we check the error variable and return the response. If response is TRUE, form will submit and else we have to display the errors. You can load the demo and change the value of error variable to 1 or 0 button and click the run button. Then click save button to see the difference.
Always use return statement in submit function.
Return true will submit the form and return false will prevent submission.

Validating Form Input Controls
Using Javascript
<script type='text/javascript'>
var name = document.getElementById('name').value;
if(name == ''){
error = 1;
alert('Name cannot be empty');
}
</script>
Using Jquery
<script type='text/javascript'>
var name = $('#name').val();
if(name == ''){
error = 1;
alert('Name cannot be empty');
}
</script>
Text Box Validation Demo
Using Javascript
<script type='text/javascript'>
var country = document.getElementById('country').value;
if(country == '0'){
error = 1;
alert('You should select a country.');
}
</script>
Using Jquery
<script type='text/javascript'>
var country = $('#country').val();
if(country == '0'){
error = 1;
alert('You should select a country.');
}
</script>
Select Box Validation Demo
Checkboxes are provided to allow users to select one or more values like “Features”. But some occassions we use single checkbox alone in the form. Best example to this is most web sites provides a checkbox in their registration forms for their privacy policy or terms of use. User cannot proceed without clicking the checkbox. Following code shows you how to validate checkbox for required. You can find more about jquery checkboxes using my tutorial jquery checkbox examples
Using Javascript
<script type='text/javascript'>
if(1(document.getElementById('checkboxid').checked)){
error = 1;
alert('Please Tick the Agree to Terms of Use.');
}
</script>
Using Jquery
<script type='text/javascript'>
if(!($('#checkboxid').is(':checked'))) {
error = 1
alert("Please Tick the Agree to Terms of Use");
}
</script>
Textareas are used for fields like descriptions,comments which needs higher number of characters. Basic validation on a textarea is required validation. Following codes will show you how to do that.
Using Javascript
<script type='text/javascript'>
var comment = document.getElementById('comment').innerHTML;
if(comment == ''){
error = 1;
alert('Comment cannot be empty.');
}
</script>
Using Jquery
<script type='text/javascript'>
var comment = $('#comment').val();
if(comment == ''){
error = 1;
alert('Comment cannot be empty.');
}
</script>
Textarea Validation Demo
<script type='text/javascript'>
$('#targets').submit(function() {
var error=0;
var name = $('#name').val();
if(name == ''){
error = 1;
alert('Name cannot be empty');
}
var country = $('#country').val();
if(country == '0'){
error = 1;
alert('You should select a country.');
}
var comment = $('#comment').val();
if(comment == ''){
error = 1;
alert('Comment cannot be empty.');
}
if(!($('#checkboxid').is(':checked'))) {
error = 1
alert("Please Tick the Agree to Terms of Use");
}
if(error){
return false;
}else{
return true;
}
});
</script>
<form id='targets' action='http://www.innovativephp.com' method='post' >
<input type='text' name='test_field' id='name' />
<select name='test_field' id='country' >
<option value='0'>Select</option>
<option value='LK'>Sri Lanka</option>
<option value='IN'>India</option>
<option value='UK'>United Kingdom</option>
</select>
<textarea name='test_field' id='comment' ></textarea>
<input type='checkbox' name='test_field' id='checkboxid' />
<input type='submit' value='Save' />
</form>
Input Field Validation Demo
Handling Error Messages On Form Submission
<script type='text/javascript'>
$('#targets').submit(function() {
var error=0;
var name = $('#name').val();
if(name == ''){
error = 1;
$('#name_error_msg').html("Name cannot be empty");
$('#name_error_msg').parent().show();
}
var country = $('#country').val();
if(country == '0'){
error = 1;
$('#country_error_msg').html('You should select a country.');
$('#country_error_msg').parent().show();
}
var comment = $('#comment').val();
if(comment == ''){
error = 1;
$('#comment_error_msg').html('Comment cannot be empty.');
$('#comment_error_msg').parent().show();
}
if(!($('#checkboxid').is(':checked'))) {
error = 1;
$('#checkboxid_error_msg').html("Please Tick the Agree to Terms of Use.");
$('#checkboxid_error_msg').parent().show();
}
if(error){
return false;
}else{
return true;
}
});
</script>
<style type='text/css'>
.label_col{
width:20%;
padding:5px;
float:left;
}
.field{
width:75%;
padding:5px;
float:left;
}
.error_field{
width:75%;
padding:5px;
float:left;
}
.error_msg{
display:none;
clear:both;
color:#f00;
}
li{
width:100%;
float:left;
}
</style>
<form id='targets' action='http://www.innovativephp.com' method='post' >
<ul>
<li ><div class='label_col'>Name</div><div class='field'><input type='text' name='test_field' id='name' /></div></li>
<li class='error_msg' >
<div class='label_col'> </div><div class='error_field' id='name_error_msg'> </div>
</li>
<li ><div class='label_col'>Country</div><div class='field'>
<select name='test_field' id='country' >
<option value='0'>Select</option>
<option value='LK'>Sri Lanka</option>
<option value='IN'>India</option>
<option value='UK'>United Kingdom</option>
</select></div>
</li>
<li class='error_msg' >
<div class='label_col'> </div><div class='error_field' id='country_error_msg'> </div>
</li>
<li ><div class='label_col'>Comment</div><div class='field'><textarea name='test_field' id='comment' ></textarea></div>
<li class='error_msg' >
<div class='label_col'> </div><div class='error_field' id='comment_error_msg'> </div>
</li>
<li ><div class='label_col'> </div><div class='field'><input type='checkbox' name='test_field' id='checkboxid' />I Agree to Terms of Use</div>
<li class='error_msg' >
<div class='label_col'> </div><div class='error_field' id='checkboxid_error_msg'> </div>
</li>
<li><div class='label_col'> </div><div class='field'><input type='submit' value='Save' /></div></li>
</ul>
</form>
Inline Error Messages Demo
<script type='text/javascript'>
$('#targets').submit(function() {
var error=0;
$('#error_group').html("");
var name = $('#name').val();
if(name == ''){
error = 1;
$('#error_group').append("<p>Name cannot be empty</p>");
}
var country = $('#country').val();
if(country == '0'){
error = 1;
$('#error_group').append("<p>You should select a country.</p>");
}
var comment = $('#comment').val();
if(comment == ''){
error = 1;
$('#error_group').append("<p>Comment cannot be empty.</p>");
}
if(!($('#checkboxid').is(':checked'))) {
error = 1;
$('#error_group').append("<p>Please Tick the Agree to Terms of Use.</p>");
}
if(error){
$('#error_group').show();
return false;
}else{
return true;
}
});
</script>
<style type='text/css'>
.label_col{
width:20%;
padding:5px;
float:left;
}
.field{
width:75%;
padding:5px;
float:left;
}
.error_field{
width:75%;
padding:5px;
float:left;
}
.error_msg{
display:none;
clear:both;
color:#f00;
}
li{
width:100%;
float:left;
}
.error_group{
background-color: #FFCCCC;
color: #5E3232;
padding:10px;
display:none;
margin:5px;
}
</style>
<form id='targets' action='http://www.innovativephp.com' method='post' > <div class='error_group' id='error_group'>
</div>
<ul>
<li ><div class='label_col'>Name</div><div class='field'><input type='text' name='test_field' id='name' /></div></li>
<li ><div class='label_col'>Country</div><div class='field'>
<select name='test_field' id='country' >
<option value='0'>Select</option>
<option value='LK'>Sri Lanka</option>
<option value='IN'>India</option>
<option value='UK'>United Kingdom</option>
</select></div>
</li>
<li ><div class='label_col'>Comment</div><div class='field'><textarea name='test_field' id='comment' ></textarea></div>
<li ><div class='label_col'> </div><div class='field'><input type='checkbox' name='test_field' id='checkboxid' />I Agree to Terms of Use</div>
<li><div class='label_col'> </div><div class='field'><input type='submit' value='Save' /></div></li>
</ul>
</form>
Group Error Messages Demo
Inline Validation Method
<script type='text/javascript'>
$('#targets').submit(function() {
var error=0;
$('#name_error_msg').html('').parent().hide();
$('#country_error_msg').html('').parent().hide();
$('#comment_error_msg').html('').parent().hide();
$('#checkboxid_error_msg').html('').parent().hide();
});
Clearing Inline Error Messages Demo
Group Validation Method
<script type='text/javascript'>
$('#targets').submit(function() {
var error=0;
$('#error_group').html("");
});
Clearing Group Error Messages Demo
<script type='text/javascript'>
$('.reset').click(function() {
$('#name_error_msg').html('').parent().hide();
$('#country_error_msg').html('').parent().hide();
$('#comment_error_msg').html('').parent().hide();
$('#checkboxid_error_msg').html('').parent().hide();
});
</script>
Clear Errors On Reset Demo
Alternative Method
<script type='text/javascript'>
$('.reset').click(function() {
$('#error_group').html("");
});
</script>
Highlighting Form Fields
<style type='text/css'>
input:focus{
background-color:#cfcfcf;
}
textarea:focus{
background-color:#cfcfcf;
}
</style>
Above code will highlight all the input and textarea fields with different background color when the focus event is occurred.
Highlight Form Fields Demo
<style type='text/css'>
input:focus{
border:2px solid #000;
}
textarea:focus{
border:2px solid #000;
}
select:focus{
border:2px solid #000;
}
</style>
Highlighting Input Fields Demo
Using Button as a Submit Button
<script type='text/javascript'>
$('#save').click(function() {
var error = 0;
var name = $('#name').val();
if (name == '') {
error = 1;
alert('Name cannot be empty');
}
if(error){
return false;
}else{
$('#targets').submit();
}
});
</script>
<form id='targets' name='targets' action='http://www.innovativephp.com' method='post' >
<input type='text' name='test_field' id='name' />
<input type='button' value='Save' id='save'/>
</form>
- Instead of calling the submit event on form, we call the onclick event of the button using jquery.
- Then we have to do the necessary validations using jquery as before.
- TIf no errors, we can submit the form by calling the submit event of the form manually.
Using Image as a Submit Button
<script type='text/javascript'>
$('#targets').submit(function() {
var error = 0;
var name = $('#name').val();
if (name == '') {
error = 1;
alert('Name cannot be empty');
}
if(error){
return false;
}else{
return true;
}
});
</script>
<form id='targets' name='targets' action='http://www.innovativephp.com' method='post' >
<input type='text' name='test_field' id='name' />
<input type='image' src='http://www.innovativephp.com/uploads/skype.png' value='Save' id='save'/>
</form>
- We can use input type=’image’ to load a image and make it as submit button.
- Important to note that we cannot use img tag as a submit button..
- Once you click on the image it will function as a normal submit button.
Email Validation Using Jquery
Minimum length of a email address is 6 characters. So I have done validation for minimum length and set the maximum length as 60. You can define your own values.
<script type='text/javascript'>
$('#targets').submit(function() {
var error = 0;
var email = $('#email').val();
var reEmail = /^[A-Za-z0-9][a-zA-Z0-9._-][A-Za-z0-9]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
if (email == '') {
error = 1;
alert('Name cannot be empty');
}else if(email.length > 60){
error = 1;
alert('Email cannot exceed 60 characters');
}else if(!reEmail.test(email)){
error = 1;
alert('Invalid Email');
}
if(error){
return false;
}else{
return true;
}
});
</script>
<form id='targets' name='targets' action='http://www.innovativephp.com' method='post' >
<input type='text' name='test_field' id='email' />
<input type='submit' value='Save' id='save'/>
</form>
Text Box Length Validation
1. Using Maxlength Attribute
In this method we can define a maxlength to limit the characters to maximum number. There is no minlength attribute. So in this method you can only define maximum number of characters.
<form id='targets' name='targets' action='http://www.innovativephp.com' method='post' >
<input type='text' name='test_field' id='name' maxlength='10' />
<input type='submit' value='Save' id='save'/>
</form>
Length Validation Demo
2. Using length Property on keyup Event
Every time you type a key on a form field and when the user releases the key, keyup event will be called. So we can call a jquery function on the keyup event and validate the number of characters using length property. This method allows you to do both min and max length validations.
<script type='text/javascript'>
$('#targets').submit(function() {
var error = 0;
var name = $('#name').val();
if (name == '') {
error = 1;
alert('Name cannot be empty');
}else if(name.length > 6 || name.length<3){
error = 1;
alert('Name should be between 3-6 characters');
}
if(error){
return false;
}else{
return true;
}
});
</script>
<form id='targets' name='targets' action='http://www.innovativephp.com' method='post' >
<input type='text' name='test_field' id='name' />
<input type='submit' value='Save' id='save'/>
</form>
Length Validation Demo
3. Using regex on keyup Event
This is similar to the previous method with the exception of regex for validation instead of textbox length property. It's always easier when you have a regex for validations.
<script type='text/javascript'>
$('#targets').submit(function() {
var error = 0;
var name = $('#name').val();
var regex_length = /^[A-Za-z0-9]{3,6}$/;
if(!regex_length.test(name)){
error = 1;
alert("Name should be between 3-6 characters");
}
if(error){
return false;
}else{
return true;
}
});
</script>
<form id='targets' name='targets' action='http://www.innovativephp.com' method='post' >
<input type='text' name='test_field' id='name' />
<input type='submit' value='Save' id='save'/>
</form>
Textarea Length Validation
<script type='text/javascript'>
$('#comment').keyup(function() {
var comment = $('#comment').val();
if(comment.length>=10){
$('#disply_count').html("Maximum Characters Reached(10 Chars)");
comment = comment.substring(0, 10);
$('#comment').val(comment);
}else{
var comment_length = comment.length;
var chars_left = parseInt(10) - parseInt(comment_length);
$('#disply_count').html(chars_left +" Characters Left");
}
});
</script>
<form id='targets' name='targets' action='http://www.innovativephp.com' method='post' >
<textarea name='test_field' id='comment' ></textarea>
<div id='disply_count'></div>
<input type='submit' value='Save' id='save'/>
</form>
Textarea Length Validation
Password Field Validation
<script type='text/javascript'>
$('#targets').submit(function() {
var error = 0;
var password = $('#password').val();
var cpassword = $('#cpassword').val();
if (password == '' || cpassword == '') {
error = 1;
alert('Please Fill Both Password and Confirm Password');
}else if(password != cpassword){
error = 1;
alert('Passwords Do No Match');
}
if(error){
return false;
}else{
return true;
}
});
</script>
<form id='targets' name='targets' action='http://www.innovativephp.com' method='post' >
Password : <input type='password' name='password' id='password' />
Confirm Password : <input type='password' name='cpassword' id='cpassword' />
<input type='submit' value='Save' id='save'/>
</form>
Password Validation Demo
Password Strength Validation - Text
In this example it will indicate 4 levels of strength based on following validation criterias.
- Weak - Less than 6 characters
- Good - 6 or more characters
- Strong - 6 or more characters with 2 of either simple,capital letter or number included
- Excellent - 6 or more characters with simple,capital letter and number included
If the password strength is weak you cannot submit the form. Otherwise you can submit the form. Excellent strength password will be more secure. Feel free to try out the following demo and get the source codes.
Password Strength Validation - Graphical
Block Content Pasting On Text Boxes
Check out the following demo and source codes to get a basic idea of validating text pasting on input elements. More detailed examples of paste event usage will be discussed under ajax validations.
Block Text Pasting
Submit Single Form To Multiple Locations
Based on user selected item assign the action url using jquery.
Form will be submitted dynamically based on assigned url.
Check out the following demo and source codes to see how it actually works. In this example i have used 4 pages of my site for form submission. You can use your own urls based on your requirement.
Submit Form To Multiple Pages


December 10th, 2011 at 7:58 pm
Hi,
Your tutorial is very complete with fully-detailed examples.
That’s an awesome place to learn jQuery validation. The jQuery validator plugin can ease both simple and complex forms too (http://bassistance.de/jquery-plugins/jquery-plugin-validation/).
December 15th, 2011 at 9:22 pm
Good one! nice and good site.