The Html.ValidationMessageFor() is a strongly typed extension method. It displays a validation message if an error exists for the specified field in the ModelStateDictionary object.

ValidationMessageFor() Signature:

MvcHtmlString ValidateMessage(Expression<Func<dynamic,TProperty>> expression, string validationMessage, object htmlAttributes)

Visit MSDN to know all the overloads of ValidationMessageFor() method.

Consider the following ValidationMessageFor() example.

Example: ValidationMessageFor

@model Student  
@Html.EditorFor(m => m.StudentName) <br />
@Html.ValidationMessageFor(m => m.StudentName, "", new { @class = "text-danger" })

In the above example, the first parameter in ValidationMessageFor method is a lambda expression to specify a property for which we want to show the error message. The second parameter is for custom error message and the third parameter is for html attributes like css, style etc.

The ValidationMessageFor() method will only display an error if you have configured DataAnnotations attribute to the specifed property in the model class. The following example is a Student model class where the DataAnnotations attribute "Required" is applied to the StudentName property.

Example: Student Model

public class Student
    public int StudentId { get; set; }
    public string StudentName { get; set; }
    public int Age { get; set; }

The above code will generate the following html.

Html Result:

<input id="StudentName" 
        value="" />

<span class="field-validation-valid text-danger" 

Now, when the user submits a form without entering the StudentName then ASP.NET MVC uses the data- attribute of Html5 for the validation and the default validation message will be injected when validation error occurs, as shown below.

Html with Validation message:

<span class="field-validation-error text-danger" 
            data-valmsg-replace="true">The StudentName field is required.</span>

The error message will appear as the image shown below.

Output of ValidationMessageFor() method

Custom Error Message:

You can display your own error message instead of the default error message as above. You can provide a custom error message either in the DataAnnotations attribute or the ValidationMessageFor() method.

Use the ErrorMessage parameter of the DataAnnotation attributes to provide your own custom error message as shown below.

Example: Custom error message in the Model

public class Student
    public int StudentId { get; set; }
    [Required(ErrorMessage="Please enter student name.")]
    public string StudentName { get; set; }
    public int Age { get; set; }

Also, you can specify a message as a second parameter in the ValidationMessage() method as shown below.

Example: Custom error message

@model Student  
@Html.Editor("StudentName") <br />
@Html.ValidationMessageFor(m => m.StudentName, "Please enter student name.", new { @class = "text-danger" })

Learn about ValidationSummary method in the next section.