Special Offer - Get $90 Discount and Host Your Dream Web Site @ Dreamhost for 1 Year Click Here. Promo Code SLJ345
Back To Top
Building Impressive Presentations with impress.js
Are you tired of creating boring Presentations?
Take a look at the the future of online presentations with impress.js
in my latest book

Mastering Jquery Form Validation Using Practical Examples

on 2011/12/4 10:43 AM stored in: Jquery and tagged: , ,

Jquery Validation Tutorial Topics


Introduction To Form Validation Techniques

Form submission and validation is a essential requirement in web application development. This allows you to filter the user input in order to preserve the integrity of your data. Their are 2 types of form validations.

1. Client Side Validation –

Done using javascript or similar client side scripting language.

Used to provide quick responses to enhance user experience. This is optional.

Cannot do database related validations.

2. Server Side Validation –

Done using PHP or similar server side language
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.
Types of Validation
  • 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

Validating before the form submission is the main technique we use in client side validation. When the submit button is clicked we have to call a javascript function and check if form data contains any errors. If errors are identified we have to stop submitting the form and display the errors back to the user.

Process of onsubmit Form Validation
1. Call the javascript function for validation when the onsubmit event is fired.
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.

 

 
Important Points To Note
Javascript onsubmit or Jquery submit function should be called to start validation before submit.
Always use return statement in submit function.
Return true will submit the form and return false will prevent submission.

 


Validating Form Input Controls

In this section I’ll show you how to access and validate commonly used input form controls. The code provided in this examples contain the javascript code only. Try the demo for the full source code.

 

Validating Text Inputs
Text boxes are the mainly used component in forms. Basic validation done on text fields is the required validation where the text field cannot be empty. Following example contains how to do required validation on a text field using javascript and jquery.

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
 

Validating Select Boxes
Basic validation on select boxes known as combo boxes is the required validation. We have to give a default option like “Select” and value like “0″ to do the required validation on a select box. Following code will show you how to validate a select box.

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
 
Validating Checkboxes

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>

Checkbox Validation Demo

 

Validating Textareas

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
 
Complete Demo For This Section
<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

Displaying Inline Error Messages
This is the latest way of displaying error messages in modern web applications. Each message is displayed inline along with the field. Inline form validation method is user friendly since users can navigate to fields with errors without searching for them by their field name. Following code will show you how to do inline validation with jquery.

<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
 

Displaying Error Message Group
This is the most commonly used method for displaying errors in web applications. All the errors are grouped into single message and displayed at the top of the form. Disadvantage of this method is that users has to look for the error using field name. Following code will show you how to display error messages as a group.

<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
 

Clearing Error Messages On Submit
Once the form is submitted we should clear messages of the fields which are validated properly. Following code will show you how to acheive this using inline method and grouping method. Only the field clearing part of the code is included. Check out the demo for complete code.

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
 

Clearing Error Messages On Reset
Reset button is used to clear all the form field values. But when the user clicks reset button we have to clear the error messages as well. We can do it by using the onclick method of reset button. Following code shows you how to clear error messages on reset.

<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

Changing the Color on Focus
In Modern web applications once the user clicks on a form element it will be displayed with different styles in order to enhance the user friendliness. Changing field color on focus event is very popular method. Following code will show you how to highlight form fields on focus.

<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
 

Changing the Border on Focus
Also we can highlight the form fields by creating a border on focus event. Use the following link and click on the fields to see it in action.

<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

Normally we use submit buttons to submit html forms to the server. In some situations we may need to use normal input buttons as submit buttons. Following code will show you how to use button to submit a form using jquery.

<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.

 

Button as Submit Demo

 

Using Image as a Submit Button

Sometimes we have to use images as submit buttons to provide a better look and feel for the highly graphical sites. In such cases we can use input type image to load the image and use it as a submit button using jquery.

<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.

 

Image as Submit Demo

 

Email Validation Using Jquery

In this section I’ll show you how to validate email addresses using jquery and regular expressions. You can replace the email regex with different email regex you have and make sure to try the demo by entering invalid email addresses and email addresses with higher and lower number of characters.

 

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>

 

Email Validation Demo

 

Text Box Length Validation

Sometimes we need to limit the allowed characters in our textboxes to certain number. We can restrict text field length to a value between minimum and maximum. Following examples will show you how to do the length validation in 3 different methods.

 

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>

 

Length Validation Demo

 

Textarea Length Validation

Textarea fields are used when we require to enter long description. If we don't limit number of characters, users will type huge descriptions which might ruin our design. So normally we limit the textareas to certain characters. Also when user type in we can display the remaining characters using jquery. Open the demo and type inside the textarea to demonstrate the validations.

 

<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

Password fields are used in most of the sign up forms. We ask the user to enter the password twice to get a confirmation. Following code will show you how to validate password and confirm password fields.

 

<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 signup forms users will always try to put simple passwords and register quickly. But those passwords may not be secure. So we can indicate and validate password strength in forms so that user will be required to enter secure password.

 

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

 

Password Strength Validation - Graphical

This example will contain the all the validations mentioned in the previous example. This will show the password strength in graphical view using a colored div. Feel free to try out the following demo and get the source codes.

Password Strength Validation

 

Block Content Pasting On Text Boxes

Normally users can paste any content copied from elsewhere to html input elements. Sometimes these content might content unacceptable characters or unicode characters we cannot validate. In such situations we can block pasting on input elements by binding the paste event to element using jquery and returning false on user paste.

 

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

In a HTML form we can set the action attribute and submit the form to the given page. In some situations we need to submit a single form to different locations based on user action. Contact form is a good example for this. We might need to submit form to different sections for support like technical.sales,inquiry. Following method is useful in such cases.

 

Important Points

You have to omit the action of the form and keep it blank
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

 

You may have browsed many websites and spent hours to find the informaion provided in this tutorial. So take 1 minute to share this post to help others find it quickly. Thank You for visiting InnovativePHP.

 

Popular Posts
Recent Posts

 

2 Responses to “Mastering Jquery Form Validation Using Practical Examples”

  1. Mancko Says:

    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/).

  2. rogwilsmith Says:

    Good one! nice and good site.

Follow Us On Facebook

Page optimized by WP Minify WordPress Plugin