Tuesday, November 3, 2009

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

<asp:DropDownList ID="ddlCountry" runat="server" AutoPostBack="True"
onselectedindexchanged="ddlCountry_SelectedIndexChanged" CausesValidation="false">
<asp:CustomValidator ID="cvCountry" runat="server" ControlToValidate="ddlCountry"
EnableClientScript="true" ValidationGroup="REG" Display="None" ErrorMessage="Country is required" Text=" "
<asp:DropDownList ID="ddlState" runat="server">
<asp:CustomValidator ID="cvState" runat="server" ControlToValidate="ddlState"
EnableClientScript="true" ValidationGroup="REG" Display="None" ErrorMessage="State is required" Text=" "

Javascript client validation function:

function validateCbo(source, args) {
var ddl = null;
ddl = document.getElementById('<%=ddlCountry.ClientID %>');
ddl = document.getElementById('<%=ddlState.ClientID %>');
if (ddl != null) {
args.IsValid = !(ddl.options[ddl.selectedIndex].value == 0);
args.IsValid = true;

No comments:

Post a Comment

Please add your valuable comments about this post if it helped you. Thanks