Custom validation error message in MVC5

13,332

Solution 1

All validation attributes within System.ComponentModel.DataAnnotations have an ErrorMessage property that you can set:

[Required(ErrorMessage = "Foo")]
[MinLength(11, ErrorMessage = "Foo"), MaxLength(11, ErrorMessage = "Foo")]
[RegularExpression("^[0-9]+$", ErrorMessage = "Foo")]

Additionally, you can still use the field name / display name for the property within the error message. This is done through a String Format setup. The following example will render an error message of "You forgot MyPropertyName".

[Required(ErrorMessage = "You forgot {0}")]
public string MyPropertyName { get; set; }

This also respects the DisplayAttribute. Since MyPropertyName isn't a very user-friendly name, the example below will render an error message of "You forgot My Property".

[Display(Name = "My Property")]
[Required(ErrorMessage = "You forgot {0}")]
public string MyPropertyName { get; set; }

And finally, you can use additional String Format values to render the values and options that are used in the more complex validation attributes, such as the MinLengthAttribute that you are using. This last example will render an error message of "The minimum length for My Property is 11":

[Display(Name = "My Property")]
[MinLength(11, ErrorMessage = "The minimum length for {0} is {1}")]
public string MyPropertyName { get; set; }

Solution 2

The RegularExpression attribute has an ErrorMessage argument.

[RegularExpression("^[0-9]+$","Error Message")]
Share:
13,332
Łukasz Trzewik
Author by

Łukasz Trzewik

Full Stack Develeroper @Gorrion Software House

Updated on June 05, 2022

Comments

  • Łukasz Trzewik
    Łukasz Trzewik almost 2 years

    I am quite new to MVC5 and asp.net and I couldn't find the answer, so I would be grateful if someone could tell me how to customize the message after failing the validation. Let's assume I have a code like this:

        [Required]
        [MaxLength(11),MinLength(11)]
        [RegularExpression("^[0-9]+$")]
    
        public string Pesel { get; set; }
    

    After using any other signs than digits I got a message like this: The field Pesel must match the regular expression '^[0-9]+$'

    How can I change this message?

  • Łukasz Trzewik
    Łukasz Trzewik about 10 years
    Thank you very much that's what i was looking for :)
  • Stephen Zeng
    Stephen Zeng over 9 years
    The syntax is incorrect. Should be [RegularExpression("^[0-9]+$", ErrorMessage = "Error Message")]
  • Romias
    Romias over 7 years
    What about internationalization?