Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  


Validate two/multiple controls with CustomValidator
To validate multiple controls at once, some have suggested using a customValidator and referencing the controls directly in the javascript validation function.

This not work if your validator is nested in a repeater, gridview, user control, or other repeating structure, because the validationfunction does not specify which controls it is validating.

Ultimately two validate multiple controls in a repeater/grid with a single CustomValidator, you would want to share one javascript function (to reduce page size) and have each validator call the function and pass the controls to validate.

There is no out of the box way to do this, but here is a workaround:

Set custom attributes on each validator on the ItemDataBound (or wherever it is loaded)

// valMatchingFields is your validator in the grid row/etc.
var valMatchingFields = e.Find<CustomValidator>("valMatchingFields");
// some random sample controls
valMatchingFields.Attributes["data-Ctrl1Id"] = ctrl1Id.ClientID;
valMatchingFields.Attributes["data-Ctrl2Id"] = ctrl2Id.ClientID;

Now, in your client function, the trick is that the validator itself is passed as argument one.
So you can reference its attributes to get back each client id you set.
By using document.getElementById you can get the input control, and .value will give you the value.

function validateMatchingFields(validator) {
var val1 = document.getElementById(validator.attributes['data-Ctrl1Id].value);
var val2 = document.getElementById(validator.attributes['data-Ctrl2Id].value);

Now you have the values of your controls, and you can set isValid as needed!

Created By: amos 4/23/2015 4:32:27 PM
Updated: 4/23/2015 4:35:15 PM