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
[StringLength(20, ErrorMessageResourceName = "StringLengthMessage", ErrorMessageResourceType = typeof(Resource))]
public string OfficePhone { get; set; }
[StringLength(20, ErrorMessageResourceName = "StringLengthMessage", ErrorMessageResourceType = typeof(Resource))]
public string CellPhone { get; set; }
and add the string resource (named StringLengthMessage
) in your resource file
"Maximum length is {1}"
Message 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:
public class MyStringLengthAttribute : StringLengthAttribute
{
public MyStringLengthAttribute() : this(20)
{
}
public MyStringLengthAttribute(int maximumLength) : base(maximumLength)
{
base.ErrorMessageResourceName = "StringLengthMessage";
base.ErrorMessageResourceType = typeof (Resource);
}
}
Or you can override FormatErrorMessage
if you want to add additional parameters. Now the properties look as follows:
[MyStringLength]
public string OfficePhone { get; set; }
[MyStringLength]
public string CellPhone { get; set; }
Try
[ StringLength(20, ErrorMessage = "Maximum length is {1}") ]
if I recall correctly that should be it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With