Wednesday 7 July, 2010

Using single ClientValidationFunction for similar validations using custom validator

Here is an example of how to write a common client validation function while using similar kind of validations on more than one asp.net control.

This example is showing how to validate two drop down list using a single javascript function for required
ASP.NET Markup
  1. <asp:DropDownList ID="ddlCountry" runat="server" AutoPostBack="True"
  2. onselectedindexchanged="ddlCountry_SelectedIndexChanged" CausesValidation="false">
  3. asp:DropDownList>
  4. <asp:CustomValidator ID="cvCountry" runat="server" ControlToValidate="ddlCountry"
  5. EnableClientScript="true" ValidationGroup="REG" Display="None" ErrorMessage="Country is required" Text=" "
  6. ClientValidationFunction="validateCbo">asp:CustomValidator>
  7. <asp:DropDownList ID="ddlState" runat="server">
  8. asp:DropDownList>
  9. <asp:CustomValidator ID="cvState" runat="server" ControlToValidate="ddlState"
  10. EnableClientScript="true" ValidationGroup="REG" Display="None" ErrorMessage="State is required" Text=" "
  11. ClientValidationFunction="validateCbo">asp:CustomValidator>

Javascript client validation function:
  1. function validateCbo(source, args) {
  2. var ddl = null;
  3. if(source.controltovalidate.indexOf('Country')>-1)
  4. ddl = document.getElementById('');
  5. else
  6. ddl = document.getElementById('');
  7. if (ddl != null) {
  8. args.IsValid = !(ddl.options[ddl.selectedIndex].value == 0);
  9. }
  10. else
  11. args.IsValid = true;
  12. }

No comments:

Post a Comment