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?
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With