How to get the 'controlToValidate' property on ClientValidationFunction?

Viewed 19008

Lets say I have this code.

<asp:TextBox ID="TextBox1" runat="server" />

<asp:CustomValidator ID="CustomValidator1" runat="server"
    ClientValidationFunction="ValidationFunction1"
    ControlToValidate="TextBox1"
    Display="Dynamic" />

And a validationFunction:

function ValidationFunction1(sender, args)
{
}

And i would like to know if, inside the function I could get the Control to validate something like:

var v = sender.ControlToValidate;
4 Answers

Here's my easy solution to be able to access the control to validate on client side. Add the regular Custom Validator control with the options you might need.

<asp:CustomValidator ID="cvalShippingRegionCountries" ErrorMessage="Choose a country" ClientValidationFunction="ClientValMultiSelectCountries" runat="server" Display="Dynamic" SetFocusOnError="true" /> 

Then, in code behind, just add a custom attribute to store the clientID of the control to validate.

cvalShippingRegionCountries.Attributes.Add("ControlToValidateClientID", multiselectShippingRegionCountries.ClientID);

Now, in the function that deals with the validation you can access the value like this:

function ClientValMultiSelectCountries(sender, args) {

        var multiselect = $find(sender.attributes.controltovalidateclientid.nodeValue);

        if ( #VALIDATION_CHECK_HERE# ) {
            args.IsValid = false;
        }
    }

You will get the clientID inside your function ;)

Related