The default ErrorMessage for StringLength validation is a lot longer than I’d like:
The field {Name} must be a string with a maximum length of {StringLength}.
I would like to change it universally to something like:
Maximum length is {StringLength}.
I’d like to avoid redundantly specifying the ErrorMessage for every string I declare:
[StringLength(20, ErrorMessage="Maximum length is 20")]
public string OfficePhone { get; set; }
[StringLength(20, ErrorMessage="Maximum length is 20")]
public string CellPhone { get; set; }
I’m pretty sure I remember there being a simple way to universally change the ErrorMessage but cannot recall it.
EDIT:
For the sake of clarification, I’m trying to universally change the default ErrorMessage so that I can input:
[StringLength(20)]
public string OfficePhone { get; set; }
and have the error message say:
Maximum length is 20.
You can specify the StringLength attribute as follows on numerous properties
and add the string resource (named
StringLengthMessage) in your resource fileMessage is defined once and has a variable place holder should you change your mind regarding the length to test against.
You can specify the following:
Update
To minimize duplication even further you can subclass StringLengthAttribute:
Or you can override
FormatErrorMessageif you want to add additional parameters. Now the properties look as follows: