Sometimes you may want to have one custom validator potentially display two different error messages depending on context. For example you may make your own date validator (perhaps to work with your own custom calendar control), and this control may first validate format ("xyz" is not a date, "12/3/2005" is), and then validate integration with the rest of the page ("Start Date occurs before End Date"). Each type of validation merits its own message. The reason you'd combine these controls is because the integration requires first performing the type validation.
Ideally we could change this at both the client and the server. We can do this with ASP 1.1's validators.
We can set the error message at the client via using the source.errormessage property:
function ValidateStuff(source, arguments)
source.errormessage = "I changed this on the fly!"; //or source.errormessageB
arguments.IsValid = false;
We can set the error message at the server via casting the source object and setting its ErrorMessage.
protected void ValidateMaxLength (object source, ServerValidateEventArgs value)
((CustomValidator)source).ErrorMessage = "This was changed at the server";
value.IsValid = false;
We can access the other error message simply by adding a attribute to the current validtor, like ErrorMessageB, and then referencing it like source.errormessageB. Check out Validation Tips for Validators for more details about this.
If you have two error messages, you'll want separate properties for each of those, i.e. have messageA and messageB. Then set source.errormessage to the appropriate one. Don't store your main message in source.errormessage because it will just get overwritten when you set it with something else.
Note that in order for this to show up, the error messages must be displayed in a ValidationSummary control.
A sample custom validator Html might be:
ErrorMessage_A = "..."
ErrorMessage_B = "..."
This is just another trick for ASP.Net validators to give you some more flexibility.
Post a Comment