Archive

Archive for the ‘ASP.NET’ Category

Pass your own arguments to the ClientValidationFunction in a CustomValidator

September 27, 2009 8 comments

When using a CustomValidator in asp.net you can specify a ClientValidationFunction to run on your client side. This function need to have 2 parameters (sender, args). The sender is the customvalidator control and the args is where you can specify the result of your validation(args.IsValid) and also access to the value of the control attached to you custom validator(args.Value). This is very useful for more complex validation on client side.

But what if you need to pass additional arguments. For example if you want to use the same client function for more than one control. Here is an option, you can add properties to your validation object, and then access them from the source parameter in your client function. Take a look at the example:

<head runat=”server”>
<title></title>
<script language=”JavaScript”>
function validateRadioButtons(sender, args) {
var radioButton1 = document.getElementById(sender.RB1);
var radioButton2 = document.getElementById(sender.RB2);
args.IsValid = radioButton1.checked != radioButton2.checked;
}
</script>
</head>

<body>
<form id=”form1″ runat=”server”>
<div>
Question 1:
<asp:RadioButton ID=”RadioButton1″ runat=”server” Text=”Yes” />
<asp:RadioButton ID=”RadioButton2″ runat=”server” Text=”No” />
<asp:CustomValidator ID=”CustomValidator1″ ClientValidationFunction=”validateRadioButtons”
runat=”server” ErrorMessage=”CustomValidator”></asp:CustomValidator>
<br />
Question 2:
<asp:RadioButton ID=”RadioButton3″ runat=”server” Text=”Yes” />
<asp:RadioButton ID=”RadioButton4″ runat=”server” Text=”No” />
<asp:CustomValidator ID=”CustomValidator2″ ClientValidationFunction=”validateRadioButtons”
runat=”server” ErrorMessage=”CustomValidator”></asp:CustomValidator>
<br />
Question 3:
<asp:RadioButton ID=”RadioButton5″ runat=”server” Text=”Yes” />
<asp:RadioButton ID=”RadioButton6″ runat=”server” Text=”No” />
<asp:CustomValidator ID=”CustomValidator4″ ClientValidationFunction=”validateRadioButtons”
runat=”server” ErrorMessage=”CustomValidator”></asp:CustomValidator>
<br />
</div>
</form>
</body>

protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterExpandoAttribute(CustomValidator1.ClientID, “RB1″, RadioButton1.ClientID, false);
Page.ClientScript.RegisterExpandoAttribute(CustomValidator1.ClientID, “RB2″, RadioButton2.ClientID, false);

Page.ClientScript.RegisterExpandoAttribute(CustomValidator2.ClientID, “RB1″, RadioButton3.ClientID, false);
Page.ClientScript.RegisterExpandoAttribute(CustomValidator2.ClientID, “RB2″, RadioButton4.ClientID, false);

Page.ClientScript.RegisterExpandoAttribute(CustomValidator3.ClientID, “RB1″, RadioButton5.ClientID, false);
Page.ClientScript.RegisterExpandoAttribute(CustomValidator3.ClientID, “RB2″, RadioButton6.ClientID, false);
}

Follow

Get every new post delivered to your Inbox.