Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...