Iterate asp.net form validators client side

I added a client side onclick function to a submit button, but wanted to verify that the form validators were all valid before performing my magic.  Unfortunately, you can’t change when the validator logic gets fired, so my onclick function always gets processed before the form validation logic.  Luckily, Microsoft provides a few client side helper methods/properties that allow you to work with the form validators.

You can enable/disable validators via the ValidatorEnable(validator, enable) function, which seems like it would be useful for complicated forms…  But for me, I wanted to iterate the validators, have them perform their logic, and then determine if any of them were invalid.  The following code block will do just that:

var isValid = true;
if (Page_Validators) {
for (var i = 0; i < Page_Validators.length; i++) {
ValidatorValidate(Page_Validators[i]);
isValid = Page_Validators[i].isvalid;
if (!isValid)
break;
}
}

 

To iterate the validators and have them display their message in a validation summary, you’d want to do something like:

var isValid = true;
if (Page_Validators) {
for (var i = 0; i < Page_Validators.length; i++) {
ValidatorValidate(Page_Validators[i]);
isValid = Page_Validators[i].isvalid;
if (isValid)
isValid = Page_Validators[i].isvalid;
}
Page_IsValid = isValid;
ValidationSummaryOnSubmit();
}

 

Hope this helps someone…

One thought on “Iterate asp.net form validators client side

Comments are closed.