Łukasz Trzewik
Łukasz Trzewik

Reputation: 1165

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?

Upvotes: 5

Views: 13874

Answers (3)

Akshay Digrase
Akshay Digrase

Reputation: 468

Giving appropriate error message is good practice because some time we set multiple validation on same property ... to Identify different validation for same property we can assign error message attribute "(ErrorMessage = 'message will be here')"
e.g.,:

[Required(ErrorMessage = "Username Must not be blank")]
[MinLength(8, ErrorMessage = "Too short Username"), MaxLength(20, ErrorMessage = "UserName must be less than 20")]
[RegularExpression("^[0-9][a-z][A-Z]+$", ErrorMessage = "Username must be combination of number,letter(Capital and Small)")]
public string UserName { get; set; }

Upvotes: 0

Jay Harris
Jay Harris

Reputation: 10065

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

Upvotes: 21

mxmissile
mxmissile

Reputation: 11681

The RegularExpression attribute has an ErrorMessage argument.

[RegularExpression("^[0-9]+$","Error Message")]

Upvotes: 1

Related Questions