Client
Side Validation with ASP Validators
If the user is working with a browser that
supports dynamic HTML (DHTML), ASP.NET validation controls can perform
validation using client script. Because the controls can provide immediate
feedback without a round trip to the server, the user experience with the page
is enhanced.
We will be using of the client side APIs amongst
the below ones :
Client Page Variable
|
Server Page Property
|
Page_IsValid
|
IsValid
|
Page_Validators (array) Contains references to all validation controls
on the page.
|
Validators (collection) Contains references to all validation
controls.
|
Page_ValidationActive A
Boolean value that indicates whether validation should take place. Set this
variable to false to turn off client-side validation
programmatically.
|
(no equivalent)
|
Code Snippet :
<asp:Label ID="UserNameLabel" runat="server">Username:</asp:Label>
<asp:TextBox ID="UserName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server"
ControlToValidate="UserName" ErrorMessage="User
Name is required." ToolTip="User Name is required." ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator>
<asp:Label ID="PasswordLabel" runat="server">Password:</asp:Label>
<asp:TextBox ID="Password" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server"
ControlToValidate="Password" ErrorMessage="Password
is required." ToolTip="Password is required." ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator>
<asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Log
In" ValidationGroup="LoginUserValidationGroup"
OnClientClick="performCheck();" />
Now we will be writing
script in our script file to check if the validations are performed correctly,
then only postback the page else show the respective error messages :
function performCheck() {
Page_ClientValidate("LoginUserValidationGroup");
if (Page_IsValid)
{
alert('it
is valid');
return true;
}
else {
alert('No
valid');
return false;
}
}
|
In other way, you can
directly use Page_ClientValidate method:
function performCheck()
{
if (Page_ClientValidate("LoginUserValidationGroup")) {
alert('it
is valid');
return true;
}
else {
alert('No
valid');
return false;
}
|