0

The RegularExpressionValidator allows us to show error messages when the data is invalid. Is it also possible for it to show different messages when the data is valid?

1
  • no it is used to validate inputs not display data. What are you trying to achieve, can you explain more? Commented Mar 7, 2012 at 17:00

1 Answer 1

1

EDIT THE SOLUTION BELOW DOESNT WORK.

The message is not visible when e.IsValid == true. I thought maybe you could solve this by setting it to visible in the ClientValidationFunction, but that doesn't work either because the JavaScript validation code that is included by asp.net executes the ClientValidationFunction and then calls a method called ValidatorUpdateDisplay which sets the visibility based on IsValid.

So... No, I don't think you can use Asp.Net validators to show messages for both valid and invalid data while still retaining the correct validation functionality when submitting your form.

You could maybe use two regex validators with inverse patterns and then some code to tell a submitted form not to fail validation for the good inputs, but your probably better off just writing a custom solution that isn't tied to the validation of the form.

Original Answer for reference

You could try creating a custom validator that changes the ErrorMessage property on the validator depending on the input.

something like this:

Markup:

<asp:CustomValidator ID="MyCustomValidator" runat="server" OnServerValidate="OnCustomValidate" ControlToValidate="MyControlToValidate"></asp:CustomValidator>

Codebehind:

protected void OnCustomValidate(object source, ServerValidateEventArgs e)
{
    var validator = (source as CustomValidator);
    var validRegex = new Regex("[a-z]");
    if (validRegex.IsMatch(e.Value))
    {
        e.IsValid = true;
        validator.ErrorMessage = "Good input";
        return;
    }
    validator.ErrorMessage = "Your input is not valid";
    e.IsValid = false;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.