Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify default ErrorMessage for StringLength validation

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.

like image 401
snumpy Avatar asked Mar 02 '12 21:03

snumpy


2 Answers

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:

  1. {0} - Name
  2. {1} - Maximum Length
  3. {2} - Minimum Length

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; }
like image 76
bloudraak Avatar answered Oct 18 '22 14:10

bloudraak


Try

[ StringLength(20, ErrorMessage = "Maximum length is {1}") ]

if I recall correctly that should be it.

like image 42
Nick Albrecht Avatar answered Oct 18 '22 16:10

Nick Albrecht