jQuery Validation With ASP.Net Web Form

Introduction

In this example we will explain the basics and widely used jQuery validation in ASP.Net Web Form. Using a library to do form validations can save much of your development time. The jQuery Form validation library is the most popular validation library and I think one of the easiest libraries to use in web forms.

For validating a web form using the jQuery validation library we need to include the following scripting file in our master page or webpage.

  1. <!--include jQuery -->  
  2. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"  
  3. type="text/javascript"></script>   
  4. <!--include jQuery Validation Plugin-->  
  5. <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/jquery.validate.min.js"  
  6. type="text/javascript"></script>  
Or you can directly link it to the project bin directory.
  1. <script src="Scripts/jquery-1.10.2.min.js"></script>  
  2. <script src="Scripts/jquery.validate.min.js"></script>  

If you are using the Visual Studio 2013 default template then jquery-1.10.2.min.js is available for your Scripts folder. Just add the reference of that. For jquery.validate.min.js you can use the CDN link or add the reference using the NuGet package manager (search for jquery.validate.min and install it).

After adding the preceding reference to your page we need to use the following syntax to defend the rule for our webpage.

In simple form, the format is like this:

    $('#formid').validate( { rules:{ }, messages:{ } } );

Using the preceding syntax we will validate our webpage. formid is the Id of our webpage for which we do the validation.

For writing our custom/validation rule we need to use the following syntax.

  1. rules:   
  2.       {  
  3.           Name_Of_Field1:   
  4.               {  
  5.                   validation_1: param_1,  
  6.                   validation_2: param_2  
  7.               }  
  8.           Name_Of_Field2:   
  9.               {  
  10.                   validation_3: param_3,  
  11.                   validation_4: param_4  
  12.               }                              
  13.       }  

Actually when the ASP.Net page is rendered in the browser the name of the control has been converted to its HTML equivalent so to access the name of the control in ASP.Net we need to use the following options.

  1. Use <%=ControlName.UniqueID %>.

  2. Use ClientIDMode="Static" inside the control and then use the id of the control.

    By default jQuery displays an error message once the validation field is something so it's recommended to customize the default error message to minimize the confusion. We need to use the following syntax to display the custom validation message based on the control.

    1. messages:   
    2.        {  
    3.            Name_Of_Field1:  
    4.                {  
    5.                    validation_1: "message for validation_1",  
    6.                    validation_2: "message for validation_2"  
    7.                }  
    8.            Name_Of_Field2:  
    9.                {  
    10.                    validation_3: "message for validation_3",  
    11.                    validation_4: "message for validation_4"  
    12.                }  
    13.        }  

    This article will explain the following validation.

    1. Required Field validation.
    2. Regular Expression Validation.
    3. Range validation.
    4. Compression Validation.
    5. Custom Validation.
    Required Field validation

      Required field validation is one of the most commonly used validations with web forms Now I will explain how we make an ASP.Net control required using jQuery.

      TextBox: For making a TextBox required we must use the following code.

      • Add the reference of jQuery scripts file and validation file as in the following:

        1. <script src="Scripts/jquery-1.10.2.min.js"></script>  
        2. <script src="Scripts/jquery.validate.min.js"></script>  
        In this case the entire scripts file is in my Scripts folder. Just drag and drop the required file and it will automatically generate the required HTML code for you.
      • After adding the reference use the following syntax for validation.

        1. <script type ="text/javascript" >          
        2. $(document).ready(function() {    
        3.     $("#form1").validate({                 
        4.              rules: {  
        5. //This section we need to place our custom rule for the control.  
        6. },  
        7.      messages: {  
        8. //This section we need to place our custom validation message for each control.  
        9.   
        10. },  
        11. });              
        12.        });     
        13.          
        14.  </script>  
      • Now inside the rules section we need to add the control name with the required rules for validation. To do that we need to add the following code.

        1. //Name of the field.  
        2. <%=IdOfTheTextBox.UniqueID %>:{  
        3.  required:true  
        4. }  
        UniqueID will provide the name of the control. We can also use the Id of the control as a control name. For that we need to use ClientIDMode="Static" . Required will make the TextBox required. The complete code will be like:
        1. <script src="Scripts/jquery-1.10.2.min.js"></script>  
        2.     <script src="Scripts/jquery.validate.min.js"></script>    
        3.     <script type ="text/javascript" >                
        4.         $(document).ready(function () {  
        5.             $("#form1").validate({  
        6.                 rules: {  
        7.                     //This section we need to place our custom rule   
        8. //for the control.  
        9.                     <%=txtName.UniqueID %>:{  
        10.                         required:true  
        11.                     },   
        12.                 },  
        13.                 messages: {  
        14.                     //This section we need to place our custom   
        15. //validation message for each control.  
        16.                       <%=txtName.UniqueID %>:{  
        17.                           required: "Name is required."  
        18.                       },  
        19.                 },  
        20.             });  
        21.         });         
        22.     </script>  
        23.     <br />  
        24.    
        25.     Name <asp:TextBox ID="txtName" runat="server"></asp:TextBox>  
        26.     <br />  
        27.     <br />  
        28.    <asp:Button ID="btnSubmit" runat="server" Text="Submit" />   

        If we run the preceding code the output will be like.

        name required

        If we did not add our custom message to the preceding control then it will display “This field is required.”. That creates confusion for the end user so it is always recommended that use your custom validation error message when validating a control.

        In general the entire error message should display in the Red color. If we want to do the same we need to add some CSS for that.

        1. <style type ="text/css" >  
        2.         label.error {             
        3.             color: red;   
        4.             display:inline-flex ;                 
        5.         }  
        6. </style>  

        Now all the errors will display in Red. Just change the color to any other color depending on your requirement.

        name required error

      DropDownList: For making a dropdown list required we must create our custom validation rule and add that rule with the dropdown list like.

      1. //custom validation rule for Dropdown List  
      2. $.validator.addMethod("CheckDropDownList"function (value, element, param) {  
      3. if (value == '0')  
      4.   return false;  
      5. else  
      6.   return true;  
      7. },"Please select a Department.");  

      Here you can change the value ==’0’ to any other if your dropdown list's first value is not zero. The complete code will be like:

      1. <script src="Scripts/jquery-1.10.2.min.js"></script>  
      2.     <script src="Scripts/jquery.validate.min.js"></script>    
      3.     <script type ="text/javascript" >                
      4.         $(document).ready(function () {  
      5.             //custom validation rule for Dropdown List  
      6.             $.validator.addMethod("CheckDropDownList"function (value, element, param) {  
      7.                 if (value == '0')  
      8.                     return false;  
      9.                 else  
      10.                     return true;  
      11.             },"Please select a Department.");    
      12.   
      13.             $("#form1").validate({  
      14.                 rules: {  
      15.   
      16.                      <%=ddlDept.UniqueID %>:{  
      17.                          CheckDropDownList:true  
      18.                      },  
      19.                 },  
      20.                 messages: {  
      21.                     //This section we need to place our custom validation message for each control.  
      22.                       
      23.                 },  
      24.             });  
      25.         });         
      26.     </script>  
      27.      <style type ="text/css" >  
      28.         label.error {             
      29.             color: red;   
      30.             display:inline-flex ;                 
      31.         }  
      32.     </style>  
      33.     <br />  
      34.    
      35.      
      36.     Department  <asp:DropDownList ID="ddlDept" runat="server">  
      37.                 </asp:DropDownList>  
      38.     <br />  
      39.     <asp:Button ID="btnSubmit" runat="server" Text="Submit" />  
      Here I am binding the dropdown list at runtime. If you want, you can hardcode the list value also, there is no need to change anything. When we run the page it will show like:

      select department

      RadioButtonList: For making a Radio Button List required we do not need to put in any extra effort, just follow the same procedure as for the TextBox.

      1. <script src="Scripts/jquery-1.10.2.min.js"></script>  
      2.     <script src="Scripts/jquery.validate.min.js"></script>    
      3.     <script type ="text/javascript" >                
      4.         $(document).ready(function () {       
      5.             $("#form1").validate({  
      6.                 rules: {  
      7.   
      8.                      <%=rbEmpLevel.UniqueID %>: {  
      9.                          required: true  
      10.                      },  
      11.                 },  
      12.                 messages: {  
      13.                     //This section we need to place our custom   
      14. //Validation message for each control.  
      15.                      <%=rbEmpLevel.UniqueID %>: {  
      16.                          required: "Skills is required."  
      17.                      },  
      18.                 },  
      19.             });  
      20.         });         
      21.     </script>  
      22.      <style type ="text/css" >  
      23.         label.error {             
      24.             color: red;   
      25.             display:inline-flex ;                 
      26.         }  
      27.     </style>  
      28.     <br />  
      29.      
      30.     Employee Level   <asp:RadioButtonList ID="rbEmpLevel"  CssClass="radioclass" runat="server" RepeatDirection="Horizontal">  
      31.                 </asp:RadioButtonList>     
      32.     <br />  
      33.     <asp:Button ID="btnSubmit" runat="server" Text="Submit" />  

      Here also I am binding the radio button list at runtime. When we run the preceding code it will show:

      skill required

      Here the error message is misplaced since we can see it clearly. For placing the error message after the radio button list we need to use the following code after the message body.

      1. //Error placement for radio buttons  
      2. errorPlacement: function(error, element)   
      3. {  
      4.   if ( element.is(":radio") )   
      5.   {  
      6.       error.appendTo( element.parents('.radioclass') );  
      7.   }    
      8. else  
      9.   { // This is the default behavior   
      10.     error.insertAfter(element );  
      11.   }  
      12. },  

      The preceding code will just adjust the error message and place it after the radio button list.

      Regular Expression Validation

      It is very simple to add a regular expression validator to jQuery validation. We just need to add one function for that like.

      1. //custom rule to check regular expression   
      2. $.validator.addMethod("match"function(value, element)   
      3. {  
      4.      return this.optional(element) || /^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/i.test(value);  
      5. }, "Please enter a valid email address.");  

      You can change the regular expression depending on your needs. The complete code will be like:

      1. <script src="Scripts/jquery-1.10.2.min.js"></script>  
      2.     <script src="Scripts/jquery.validate.min.js"></script>    
      3.     <script type ="text/javascript" >                
      4.         $(document).ready(function () {  
      5.             //custom rule to check regular expression   
      6.             $.validator.addMethod("match"function(value, element)   
      7.             {  
      8.                 return this.optional(element) || /^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/i.test(value);  
      9.             }, "Please enter a valid email address.");   
      10.             $("#form1").validate({                 
      11.                 rules: {  
      12.   
      13.                      <%=txtEmailId.UniqueID %>: {  
      14.                          match: true  
      15.                      },  
      16.                 },  
      17.                 messages: {  
      18.                     //This section we need to place our custom validation message for each control.  
      19.                       
      20.                 },  
      21.                  
      22.             });  
      23.         });         
      24.     </script>  
      25.      <style type ="text/css" >  
      26.         label.error {             
      27.             color: red;   
      28.             display:inline-flex ;                 
      29.         }  
      30.     </style>  
      31.     <br />  
      32.      
      33.     Email Id   <asp:TextBox ID="txtEmailId" runat="server" CausesValidation="True" ></asp:TextBox>   
      34.     <br />  
      35.     <asp:Button ID="btnSubmit" runat="server" Text="Submit" />  
      When we run the preceding code it will show the following output:

      enter valid email

      Note: Actually for email id there is no need to add a regular expression validator. jQuery provides a default rule, we just need to enable that rule. For example I have used the preceding code.

      email: true

      It will also validate the email id without using a regular expression. A regular expression will be very useful when we want to apply our custom syntax on a TextBox.

      In the same way we can also validate an URL using:

      url: true // It will validate the valid URL
      digits: true // It will only accept Number Input.
      date: true // It will only accept valid date format Input.

      Range validation

      It's very simple to use range validation in jQuery. jQuery has some built-in range validation rules, we just need to use them. There are the following range validations in jQuery:

      • range: [20, 25] // It will only accept Number between 20 to 25.

      • minlength: 10, // Minimum length of the TextBox is 10.

      • maxlength: 20// Maximum length of the TextBox is 20.

      • rangelength: [10, 20] // TextBox only accepts a minimum of 10 and a max of 20 characters.

      Note: rangelength will not validate the TextBox when the TextBox is null; the same for range also.

      Complete sample code:

      1. <script src="Scripts/jquery-1.10.2.min.js"></script>  
      2.     <script src="Scripts/jquery.validate.min.js"></script>    
      3.     <script type ="text/javascript" >                
      4.         $(document).ready(function () {              
      5.             $("#form1").validate({                 
      6.                 rules: {  
      7.                      <%=txtAge.UniqueID %>: {                           
      8.                          range: [10, 20],                           
      9.                      },  
      10.                 },  
      11.                 messages: {  
      12.                     //This section we need to place our custom validation message for each control.  
      13.                     <%=txtAge.UniqueID %>: {  
      14.                         range: "Age should be between {0} and {1}"  
      15.                     },  
      16.                 },                 
      17.             });  
      18.         });         
      19.     </script>  
      20.      <style type ="text/css" >  
      21.         label.error {             
      22.             color: red;   
      23.             display:inline-flex ;                 
      24.         }  
      25.     </style>  
      26.     <br />  
      27.      
      28.     Age   <asp:TextBox ID="txtAge" runat="server" CausesValidation="True" ></asp:TextBox>   
      29.     <br />  
      30.     <asp:Button ID="btnSubmit" runat="server" Text="Submit" />  
      When we run the code it will show the following output.

      enter age

      Compression Validation

      Using the following example we can achieve compression validation.

      1. <script src="Scripts/jquery-1.10.2.min.js"></script>  
      2.     <script src="Scripts/jquery.validate.min.js"></script>    
      3.     <script type ="text/javascript" >                
      4.         $(document).ready(function () {              
      5.             $("#form1").validate({                 
      6.                 rules: {  
      7.                      <%=txtcid.UniqueID %>: {   
      8.                          required: true,  
      9.                          equalTo: "#<%=txtemailId.ClientID %>" // Id of the control to compare.                         
      10.                      },  
      11.                 },  
      12.                 messages: {  
      13.                     //This section we need to place our custom validation message for each control.  
      14.                     <%=txtcid.UniqueID %>: {  
      15.                         equalTo: "Enter Same Email Id."  
      16.                     },  
      17.                 },                 
      18.             });  
      19.         });         
      20.     </script>  
      21.      <style type ="text/css" >  
      22.         label.error {             
      23.             color: red;   
      24.             display:inline-flex ;                 
      25.         }  
      26.     </style>  
      27.     <br />  
      28.      
      29.     Email Id                    
      30.     <asp:TextBox ID="txtemailId" runat="server" CausesValidation="True" ></asp:TextBox>   
      31.     <br />  
      32.     Comferm Email Id   <asp:TextBox ID="txtcid" runat="server" CausesValidation="True" ></asp:TextBox>   
      33.     <br />  
      34.     <asp:Button ID="btnSubmit" runat="server" Text="Submit" />  

      When we run the page it will show like:

      same emailid

      We can also check other comparison validation by creating our custom rule. I already showed how to add a custom rule with jQuery validation.

      Custom Validation

      We can also make an Ajax call and check some condition depending on our needs. In the following example I am checking whether the email id is available or not. If the email id is available then it should show an error message and restrict the form from posting to the server. For doing that we need to use the following procedure.

      • Step 1: Create a web services and check email availability in the database.

        I have created a web service (EmployeeServices.asmx) and added the following method to that.

        1. [WebMethod]  
        2. public bool IsEmailIdAvailable(string emailId)  
        3. {  
        4.     bool ret = false;  
        5.     try  
        6.     {  
        7.         using (EmployeeDbContext db = new EmployeeDbContext())  
        8.         {  
        9.             ret = !db.EmployeeDetails.Any(x => x.EmailId.Equals(emailId));  
        10.         }  
        11.         return ret;  
        12.     }  
        13.     catch  
        14.     {  
        15.         return false;  
        16.     }  
        17. }   
        The preceding method will check for email id availability in the database and if it is available then it will return false otherwise true. Here I am using Entity Framework. You can use any other. Just remember that if the record is available then the method should return false otherwise true. 
      • Step 2: Call this web service method under remote attribute in jQuery validation like.

        1. <script src="Scripts/jquery-1.10.2.min.js"></script>  
        2.     <script src="Scripts/jquery.validate.min.js"></script>    
        3.     <script type ="text/javascript" >          
        4.         $(document).ready(function() {   
        5.             $("#form1").validate({                 
        6.                 rules: {                     
        7.                     <%=txtemailId.UniqueID %>: {  
        8.                         required: true,  
        9.                         remote: function () {  
        10.                             return {  
        11.                                 url: '<%= ResolveUrl("~/EmployeeServices.asmx/IsEmailIdAvailable") %>'//URL of asmx file.                                 
        12.                                 type: "POST",  
        13.                                 contentType: "application/json; charset=utf-8",  
        14.                                 dataType: "json",  
        15.                                 data: JSON.stringify({ emailId: $('#txtemailId').val() }),                                  
        16.                                 dataFilter: function (data) {  
        17.                                     var msg = JSON.parse(data);  
        18.                                     if (msg.hasOwnProperty('d'))  
        19.                                         return msg.d;  
        20.                                     else  
        21.                                         return msg;  
        22.                                 }  
        23.                             }  
        24.                         }  
        25.                     },                            
        26.                 },                                 
        27.                 messages: {                      
        28.                    <%=txtemailId.UniqueID %>: {  
        29.                         required: "Email Id is Required",  
        30.                         remote: "This Email Id is already in use",  
        31.                     },  
        32.                },                             
        33.             });              
        34.         });     
        35.          
        36.     </script>  
        37.      <style type ="text/css" >  
        38.         label.error {             
        39.             color: red;   
        40.             display:inline-flex ;                 
        41.         }  
        42.     </style>  
        43.     <br />  
        44.      
        45.     Email Id   <asp:TextBox ID="txtemailId" runat="server" CausesValidation="True" ClientIDMode="Static" ></asp:TextBox>   
        46.     <br />  
        47.     <br />  
        48.     <asp:Button ID="btnSubmit" runat="server" Text="Submit" />  
        When we run the page it will check for email id availability in the database. If it is available then the following error message will show.

        emailid used

      Summary

      In this illustration you came to understand the basics of jQuery validation with ASP. NET web forms.

      Up Next
        Ebook Download
        View all
        Learn
        View all