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.
- <!--include jQuery -->
- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"
- type="text/javascript"></script>
- <!--include jQuery Validation Plugin-->
- <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/jquery.validate.min.js"
- type="text/javascript"></script>
Or you can directly link it to the project bin directory.
- <script src="Scripts/jquery-1.10.2.min.js"></script>
- <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.
- rules:
- {
- Name_Of_Field1:
- {
- validation_1: param_1,
- validation_2: param_2
- }
- Name_Of_Field2:
- {
- validation_3: param_3,
- validation_4: param_4
- }
- }
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.
- Use <%=ControlName.UniqueID %>.
- 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.
- messages:
- {
- Name_Of_Field1:
- {
- validation_1: "message for validation_1",
- validation_2: "message for validation_2"
- }
- Name_Of_Field2:
- {
- validation_3: "message for validation_3",
- validation_4: "message for validation_4"
- }
- }
This article will explain the following validation.
- Required Field validation.
- Regular Expression Validation.
- Range validation.
- Compression Validation.
- 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:
- <script src="Scripts/jquery-1.10.2.min.js"></script>
- <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.
- <script type ="text/javascript" >
- $(document).ready(function() {
- $("#form1").validate({
- rules: {
-
- },
- messages: {
-
-
- },
- });
- });
-
- </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.
-
- <%=IdOfTheTextBox.UniqueID %>:{
- required:true
- }
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:
- <script src="Scripts/jquery-1.10.2.min.js"></script>
- <script src="Scripts/jquery.validate.min.js"></script>
- <script type ="text/javascript" >
- $(document).ready(function () {
- $("#form1").validate({
- rules: {
-
-
- <%=txtName.UniqueID %>:{
- required:true
- },
- },
- messages: {
-
-
- <%=txtName.UniqueID %>:{
- required: "Name is required."
- },
- },
- });
- });
- </script>
- <br />
-
- Name <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
- <br />
- <br />
- <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
If we run the preceding code the output will be like.
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.
- <style type ="text/css" >
- label.error {
- color: red;
- display:inline-flex ;
- }
- </style>
Now all the errors will display in Red. Just change the color to any other color depending on your requirement.
DropDownList: For making a dropdown list required we must create our custom validation rule and add that rule with the dropdown list like.
-
- $.validator.addMethod("CheckDropDownList", function (value, element, param) {
- if (value == '0')
- return false;
- else
- return true;
- },"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:
- <script src="Scripts/jquery-1.10.2.min.js"></script>
- <script src="Scripts/jquery.validate.min.js"></script>
- <script type ="text/javascript" >
- $(document).ready(function () {
-
- $.validator.addMethod("CheckDropDownList", function (value, element, param) {
- if (value == '0')
- return false;
- else
- return true;
- },"Please select a Department.");
-
- $("#form1").validate({
- rules: {
-
- <%=ddlDept.UniqueID %>:{
- CheckDropDownList:true
- },
- },
- messages: {
-
-
- },
- });
- });
- </script>
- <style type ="text/css" >
- label.error {
- color: red;
- display:inline-flex ;
- }
- </style>
- <br />
-
-
- Department <asp:DropDownList ID="ddlDept" runat="server">
- </asp:DropDownList>
- <br />
- <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:
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.
- <script src="Scripts/jquery-1.10.2.min.js"></script>
- <script src="Scripts/jquery.validate.min.js"></script>
- <script type ="text/javascript" >
- $(document).ready(function () {
- $("#form1").validate({
- rules: {
-
- <%=rbEmpLevel.UniqueID %>: {
- required: true
- },
- },
- messages: {
-
-
- <%=rbEmpLevel.UniqueID %>: {
- required: "Skills is required."
- },
- },
- });
- });
- </script>
- <style type ="text/css" >
- label.error {
- color: red;
- display:inline-flex ;
- }
- </style>
- <br />
-
- Employee Level <asp:RadioButtonList ID="rbEmpLevel" CssClass="radioclass" runat="server" RepeatDirection="Horizontal">
- </asp:RadioButtonList>
- <br />
- <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:
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.
-
- errorPlacement: function(error, element)
- {
- if ( element.is(":radio") )
- {
- error.appendTo( element.parents('.radioclass') );
- }
- else
- {
- error.insertAfter(element );
- }
- },
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.
-
- $.validator.addMethod("match", function(value, element)
- {
- return this.optional(element) || /^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/i.test(value);
- }, "Please enter a valid email address.");
You can change the regular expression depending on your needs. The complete code will be like:
- <script src="Scripts/jquery-1.10.2.min.js"></script>
- <script src="Scripts/jquery.validate.min.js"></script>
- <script type ="text/javascript" >
- $(document).ready(function () {
-
- $.validator.addMethod("match", function(value, element)
- {
- return this.optional(element) || /^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/i.test(value);
- }, "Please enter a valid email address.");
- $("#form1").validate({
- rules: {
-
- <%=txtEmailId.UniqueID %>: {
- match: true
- },
- },
- messages: {
-
-
- },
-
- });
- });
- </script>
- <style type ="text/css" >
- label.error {
- color: red;
- display:inline-flex ;
- }
- </style>
- <br />
-
- Email Id <asp:TextBox ID="txtEmailId" runat="server" CausesValidation="True" ></asp:TextBox>
- <br />
- <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
When we run the preceding code it will show the following output:
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:
- <script src="Scripts/jquery-1.10.2.min.js"></script>
- <script src="Scripts/jquery.validate.min.js"></script>
- <script type ="text/javascript" >
- $(document).ready(function () {
- $("#form1").validate({
- rules: {
- <%=txtAge.UniqueID %>: {
- range: [10, 20],
- },
- },
- messages: {
-
- <%=txtAge.UniqueID %>: {
- range: "Age should be between {0} and {1}"
- },
- },
- });
- });
- </script>
- <style type ="text/css" >
- label.error {
- color: red;
- display:inline-flex ;
- }
- </style>
- <br />
-
- Age <asp:TextBox ID="txtAge" runat="server" CausesValidation="True" ></asp:TextBox>
- <br />
- <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
When we run the code it will show the following output.
Compression Validation
Using the following example we can achieve compression validation.
- <script src="Scripts/jquery-1.10.2.min.js"></script>
- <script src="Scripts/jquery.validate.min.js"></script>
- <script type ="text/javascript" >
- $(document).ready(function () {
- $("#form1").validate({
- rules: {
- <%=txtcid.UniqueID %>: {
- required: true,
- equalTo: "#<%=txtemailId.ClientID %>"
- },
- },
- messages: {
-
- <%=txtcid.UniqueID %>: {
- equalTo: "Enter Same Email Id."
- },
- },
- });
- });
- </script>
- <style type ="text/css" >
- label.error {
- color: red;
- display:inline-flex ;
- }
- </style>
- <br />
-
- Email Id
- <asp:TextBox ID="txtemailId" runat="server" CausesValidation="True" ></asp:TextBox>
- <br />
- Comferm Email Id <asp:TextBox ID="txtcid" runat="server" CausesValidation="True" ></asp:TextBox>
- <br />
- <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
When we run the page it will show like:
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.
- [WebMethod]
- public bool IsEmailIdAvailable(string emailId)
- {
- bool ret = false;
- try
- {
- using (EmployeeDbContext db = new EmployeeDbContext())
- {
- ret = !db.EmployeeDetails.Any(x => x.EmailId.Equals(emailId));
- }
- return ret;
- }
- catch
- {
- return false;
- }
- }
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.
- <script src="Scripts/jquery-1.10.2.min.js"></script>
- <script src="Scripts/jquery.validate.min.js"></script>
- <script type ="text/javascript" >
- $(document).ready(function() {
- $("#form1").validate({
- rules: {
- <%=txtemailId.UniqueID %>: {
- required: true,
- remote: function () {
- return {
- url: '<%= ResolveUrl("~/EmployeeServices.asmx/IsEmailIdAvailable") %>',
- type: "POST",
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- data: JSON.stringify({ emailId: $('#txtemailId').val() }),
- dataFilter: function (data) {
- var msg = JSON.parse(data);
- if (msg.hasOwnProperty('d'))
- return msg.d;
- else
- return msg;
- }
- }
- }
- },
- },
- messages: {
- <%=txtemailId.UniqueID %>: {
- required: "Email Id is Required",
- remote: "This Email Id is already in use",
- },
- },
- });
- });
-
- </script>
- <style type ="text/css" >
- label.error {
- color: red;
- display:inline-flex ;
- }
- </style>
- <br />
-
- Email Id <asp:TextBox ID="txtemailId" runat="server" CausesValidation="True" ClientIDMode="Static" ></asp:TextBox>
- <br />
- <br />
- <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.
Summary
In this illustration you came to understand the basics of jQuery validation with ASP. NET web forms.