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 Answer
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;
}