Note
- To use jQuery in an ASP.Net form you need to add the reference for the jQuery library that is nothing but a JavaScript file
- You can download the latest jQuery library from http://jquery.com/download/
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 the 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 the 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 web site 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).
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>
Password
</td>
<td>
<asp:TextBox ID="txtPass1" runat="server" TextMode="Password"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Confirm Password
</td>
<td>
<asp:TextBox ID="txtPass2" runat="server" TextMode="Password"></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 the 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:
Look at the preceding source code closely; see the ids of the controls that play the 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 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 the 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, pass, gender, conpass, EmailId, emailExp;
Name = $("#txtUserId").val();
gender = $("#ddlType").val();
pass = $("#txtPass1").val();
conpass = $("#txtPass2").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 condition will be as follows:
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 condition will be as follows:
if (Name == '' && gender == 0 && pass == '' && conpass == '' && 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 gives you the second page directly. Therefore the return false statement works similar to the Required Field validator of ASP.Net.
I hope you understand the concept.
The condition that checks both text boxes for the password are as in the following:
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 gives you the second page directly. Therefore the return false statement works similar to the Required Field validator of ASP.Net.
I hope you understand the concept.
The condition that checks both text boxes for the password are as in the following:
if (pass != conpass)
{
alert( "Password not match");
return false;
}
In the preceding condition, we are checking that the two texboxes have passwords, in other words the password and confirm password.
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 () The entire function will be as follows:
{
$('#btnSave').click(function ()
{
var Name, pass, gender, conpass, EmailId, emailExp;
Name = $("#txtUserId").val();
gender = $("#ddlType").val();
pass = $("#txtPass1").val();
conpass = $("#txtPass2").val();
EmailId = $("#txtmail").val();
emailExp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([com\co\.\in])+$/;
if (Name == '' && gender == 0 && pass == '' && conpass == '' && 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 (pass == '')
{
alert("Please Enter Password");
return false;
}
if (pass != '' && conpass == '')
{
alert("Please Confirm Password");
return false;
}
if (pass != conpass)
{
alert("Password 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
<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
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 libarary 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:
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 libarary 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 clearly see that even I have written the code on the create button to redirect to the next page but it will not be redirected because the form data is blank and it does not satisfy our validation condition that we set.
In other words, it's clear that the validation is done at the client-side in the browser level and only validates the data; it will execute the server-side code.
Now enter the invalid Email Id, it will show the following message:
Now enter the password that does not match the confirm password, 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 suggestion 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.
No comments:
Post a Comment