How to use html.ValidationMessageFor

It was silly simple…..I just didn’t add the ErrorMessage field as part of the [Required] decorator. For example:

[Required(ErrorMessage = "First name is required")]
[StringLength(30, ErrorMessage = "Name can be no larger than 30 characters")]
public string F_Name { get; set; }

[Required(ErrorMessage = "Last name is required")]
[StringLength(30, ErrorMessage = "Name can be no larger than 30 characters")]
public string L_Name { get; set; }

Now, if a user either doesn’t enter anything in the name fields, or enters something over 30 characters, the Post method doesn’t get executed and the user gets a little message telling them what’s wrong.

Leave a Comment