Thursday, April 4, 2013

ASP.NET Custom Validator

Asp.Net Custom validator allows us to validate the controls on page on client side as well as server side, But mainly the validation is done on client side through javascript.

In this article, I will explain the custom validator to validate check boxes using client validation function.

Add 2 check box controls on the page as follows:

  <asp:CheckBox ID="chkMobileAlerts" runat="server" />  
             Sign up for Mobile Alerts<br/>  
 <asp:CheckBox ID="chkTermsConditions" runat="server" />  
             I agree to Terms and Conditions  

Add a custom validation control as follows:

  <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please sign up for mobile alerts and agree to terms and conditions." 
               ValidationGroup="1" ClientValidationFunction="ValidateCheckBoxes"></asp:CustomValidator>  <br />

Client validation function is written in javascript as follows:

  <script lang="javascript">  
             function ValidateCheckBoxes(source, arguments) {  
               if (document.getElementById("<%=chkMobileAlerts.ClientID%>").checked == true && document.getElementById("<%=chkTermsConditions.ClientID%>").checked == true)  
                 arguments.IsValid = true;  
               else  
                 arguments.IsValid = false;  
             }  
           </script>  

And we're done. Run the code in browser on following button click.

  <asp:Button ID="btnRegister" runat="server" Text="Click Here to Register" ValidationGroup="1" OnClick="btnRegister_Click" CssClass="submit" />  


No comments:

Post a Comment