Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom validation error message in MVC5

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?

like image 813
Łukasz Trzewik Avatar asked Mar 24 '14 13:03

Łukasz Trzewik


1 Answers

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; }
like image 181
Jay Harris Avatar answered Oct 29 '22 19:10

Jay Harris