views:

288

answers:

1

Is there a method to stop validators from being evaluated if a previous validator is found to be not valid - at a control level?

For example, if I create a text box with a RequiredFieldValidator, a RegularExpressionValidator and a custom validator, I do not want the custom validator to be evaluated if the RequiredFieldValidator or RegularExpressionValidator have already determined that the input is invalid.

Specifically, in this case, the custom validator does not have client side support, but I would like to prevent the postback if no data is entered (using the RequiredFieldValidator) rather than having the postback take place.

+1  A: 

Both RegularExpressionValidator and RequiredFieldValidator returns true if the text box is empty. In other words: They are by default not validating empty your empty text box, so with you are doing the correct thing and it should work as expected out of the box.

The RequiredFieldValidator and the RegularExpressionValidator will by default also validate client side - using JavaScript - so no postback will occur if either of them fails.

Remember to test your regular expression string both client side and server side, since JavaScript and .NET regex'es are not 100 % compatible.

It is a good practice to define ValidationGroup on all your controls, including the buttons that should trigger the validation. This should enable server side validation, but I am not 100 % sure, so if your CustomValidator is not triggeren add the following code as the first lines of your myButton_Click method:

myButton_Click(object Sender, EventArgs e)
{
    Page.Validate("MyValidationGroup");
    if (!Page.IsValid)
    {
        return;
    }

    // ...
}

Page.Validate() accepts a validationGroup as parameter.

Jan Aagaard
You are correct; the out of the box functionality does exactly what I wanted, unfortunately the button being used to cause the postback had inadvertantly been marked as CausesValidation="False" and I did not notice. This is why the postback was taking place as the validators were not actually being evaluated client side!
Martin Robins