Background
In my previous article, we learned how to do validation Using JavaScript with a basic introduction. There are many disadvantages of using JavaScript that we will discuss later. In this article, we will learn how to do ASP.Net form validation using jQuery.
If you are a beginner or student then please read my previous article.
ASP.Net Form Validation Using JavaScript
I hope you have read the preceding article. Let us now start with the creation of the function in jQuery.
Note
- To use jQuery in an ASP.Net form you need to add the reference for the jQuery library which is nothing but a JavaScript file
- You can download the latest jQuery library from http://jquery.com/download/
Creating the function in jQuery
The function is created in jQuery using the following syntax.
Syntax
$(document).ready(function () {
$('#btnSave').click(function () {
})
});
In the preceding syntax, the function is the keyword provided by jQuery to declare a function followed by a "$" (dollar) symbol, and the "$('#btnSave').click" means that this function is called on the ASP.Net button click that has the id "btnSave".
Example
$(document).ready(function () {
$('#btnSave').click(function () {
alert("button is clicked")
})
});
I hope you now understand the basics of validation in jQuery. Let us now create one sample web application that demonstrates how to do validation.
Let us first create the web application with two web pages as in the following.
- "Start", "All Programs", "Microsoft Visual Studio 2010"
- "File", "New Website", "C# - Empty website" (to avoid adding a master page)
- Give the website a name, such as Validation or whatever you wish, and specify the location
- Then right-click on the solution in the Solution Explorer then select "Add New Item" - "Default.aspx page" (add two pages).
We are adding two web pages because our requirement is, that on the first web page, there is form data to be filled in by the user and only after validating the form data, the form will be redirected to the next page.
The first-page source code <body> tag will look as in the following.
<body bgcolor="#3366ff">
<form id="form2" runat="server">
<br />
<br />
<div>
<table>
<tr>
<td>
Name
</td>
<td>
<asp:TextBox ID="txtUserId" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Email Id
</td>
<td>
<asp:TextBox ID="txtmail" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Gender
</td>
<td>
<asp:DropDownList ID="ddlType" runat="server">
<asp:ListItem Value="0">-Select-</asp:ListItem>
<asp:ListItem Value="1">Male</asp:ListItem>
<asp:ListItem Value="2">Female</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
word
</td>
<td>
<asp:TextBox ID="txt1" runat="server" TextMode="word"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Confirm word
</td>
<td>
<asp:TextBox ID="txt2" runat="server" TextMode="word"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnSave" runat="server" Text="Create" />
<asp:Button ID="Button1" runat="server" Text="Reset" />
</td>
</tr>
</table>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
Look at the preceding source code closely; see the IDs of the controls that play an important role in JavaScript validation by reading the ASP.Net control values in JavaScript code.
The design view of the preceding source code will look as in the following.
I hope you have created the same form for demonstration purposes as above.
Reading ASP.Net Control values in jQuery
We can read ASP.Net control values in jQuery using the following syntax starting form the "$" symbol followed by the "#" symbol and control ID as in the following.
$("#txtUserId").val(
How to add the .js file?
Right-click on Solution Explorer then select "Add New Item" Then in the "script.js" page rename the .js page as you wish, I have renamed it to "UserValidation.js".
Now declare the variable inside the function using the var keyword to read the ASP.Net control values by their IDs and assign the values to the variable as.
$(document).ready(function () {
$('#btnSave').click(function () {
var Name, gender, con, EmailId, emailExp;
Name = $("#txtUserId").val();
gender = $("#ddlType").val();
= $("#txt1").val();
con = $("#txt2").val();
EmailId = $("#txtmail").val();
emailExp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([com\co\.\in])+$/;
});
});
In the code above I have taken the ASP.Net control's values in variables so it cannot be repeated again and again in our function the emailExp variable holds the pattern of the email ID in the form of a regular expression.
Now add the condition to ensure that all controls have a value, if the values are not entered in the form control then it will show a message. The conditions will be as follows.
if (Name == '' && gender == 0 && == '' && con == '' && EmailId == '') {
alert("Enter All Fields");
return false;
}
In the preceding condition, to ensure that the form control's values are blank the message "Enter All Fields" is shown to the user and finally, we are returning false; that is very important.
Importance of returning false
It's very important to use the return false statement after the condition block that returns false so if validation determines that the business requirements are not met then the form cannot be submitted. If you do not return false then the message will be displayed to the user that all fields are required but the form will be posted back and it will give you the second page directly. Therefore the return false statement works similarly to the Required Field validator of ASP.Net.
I hope you understand the concept.
The condition that checks both text boxes for the word is as in the following.
if (!= con) {
alert("word not match");
return false;
}
In the preceding condition, we are checking that the two text boxes have words, in other words, the word and confirm the word.
Condition to determine if the email address is valid.
if (EmailId != '') {
if (!EmailId.match(emailExp)) {
alert("Invalid Email Id");
return false;
}
}
In the preceding condition, first, we ensure that the email ID is not blank then we match the email ID entered into the text box to the Regular Expression that is saved in the emailExp variable.
The entire function will be as follows.
$(document).ready(function() {
$('#btnSave').click(function() {
var Name, gender, con, EmailId, emailExp;
Name = $("#txtUserId").val();
gender = $("#ddlType").val();
= $("#txt1").val();
con = $("#txt2").val();
EmailId = $("#txtmail").val();
emailExp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([com\co\.\in])+$/;
if (Name == '' && gender == 0 && == '' && con == '' && EmailId == '') {
alert("Enter All Fields");
return false;
}
if (Name == '') {
alert("Please Enter Login ID");
return false;
}
if (gender == 0) {
alert("Please Select gender");
return false;
}
if ( == '') {
alert("Please Enter word");
return false;
}
if ( != '' && con == '') {
alert("Please Confirm word");
return false;
}
if ( != con) {
alert("word not match");
return false;
}
if (EmailId == '') {
alert("Email Id Is Required");
return false;
}
if (EmailId != '') {
if (!EmailId.match(emailExp) {
alert("Invalid Email Id");
return false;
}
}
return true;
});
});
Add the reference of the external jQuery file and the jQuery Library file into the Head section of the ASP.Net form.
Just drag the .js file from the Solution Explorer to the Head section of the ASP.Net form that automatically adds the file reference path, it will look as the following.
<head id="Head1" runat="server">
<script src="jquery-2.0.3.js" type="text/javascript"></script>
<script src="UserValidation.js" type="text/javascript">
</script>
</head>
Calling jQuery function
To call the jQuery function on the ASP.Net button we do not need to call the function in the ASP.Net button's OnClientClick property that we have called in JavaScript because whenever we write the code inside the "$(document).ready(function()" function we just need to specify the control event in which the event of the control of the jQuery function will fire.
In the following example, I have called the function on the button click event that I have specified by using the control ID.
Example
$(document).ready(function () {
$('#btnSave').click(function () {
})
});
I hope you have understood it.
In our demo application, there are two ASP.Net pages, "UserCreation.aspx" and "UserLanding.aspx" along with the "UserValidation.js" JavaScript file and the Ajax library JavaScript file. In the "UserCreation.aspx" page the user enters the form details and then only after validating the details the page is redirected to the "UserLanding.aspx" page.
Use the following code in the create button.
protected void btn_Click(object sender, EventArgs e)
{
Response.Redirect("UserLanding.aspx");
}
In the code above, only after validating the form data, the page is redirected to the "UserLanding.aspx" page.
Now run the ASP.Net web application and click on the "Create" button without inserting any data in the form. It will then show the following alert message.
In the preceding screen, you see that even though I have written the code on the create button to redirect to the next page it will not be redirected because the form data is blank and it does not satisfy the validation condition that we set.
In other words, it's clear that the validation is done at the client-side at the browser level and only validates the data; it will execute the server-side code.
Now enter the invalid Email ID, and it will show the following message.
Now enter the word that does not match the confirmed word, and it will show the following message.
Now enter the valid details.
Now click on the "Create" button; it will redirect to the next page as in the following.
Note. For detailed code please download the zip file attached above.
Summary
From all the examples above we see how to validate the form data using jQuery. I hope this article is useful for all students and beginners. If you have any suggestions related to this article then please contact me. My next article explains the advantages and disadvantages of validating the form data using jQuery and JavaScript.