ASP.NET MVC ValidationMessageFor

In the previous tutorial, we learnt about the Html.ValidationMessage() helper function, used in displaying validation messages. Here we will discuss the Html.ValidationMessageFor() function.

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

ValidationMessageFor() Signature

The ValidationMessageFor() has the following function signature:

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

Just like other methods, the ValidationMessageFor() can be overloaded, and a comprehensive details of its overload can be found in the MSDN documentation.

Consider the following ValidationMessageFor() example.

//Example: ValidationMessageFor
@model Activity  
@Html.EditorFor(a => a.ActivityName) <br/>
@Html.ValidationMessageFor(a => a.ActivityName, "", new { @class = "text-danger" })

In the example above, the first parameter in ValidationMessageFor method is a lambda expression which specifies a property for which we want to display the error message on. The second parameter is for custom error message which we left blank and the third parameter is for CSS classes and other html attributes.

The ValidationMessageFor() method can only display an error if you have configured DataAnnotations attribute to the specified property in the model class.

The following example is an Activity model class where the DataAnnotations attribute "Required" is applied to the ActivityName property.

//Example: Activity Model
public class Activity
    public int Id {get; set;}
    public string ActivityName {get; set;}
    public int Status {get; set;}

The code above will generate the html below

Html Result:

<input id="ActivityName" 
        name=" ActivityName" 
        value="" />

<span class="field-validation-valid text-danger" 
        data-valmsg-for=" ActivityName" 

Now, when the user clicks the submit button of a form without entering the ActivityName, the 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 ActivityName field is required.</span>

Custom Error Message

We can display our own error message instead of the default error messages as in the above example. This custom error messages can provided either in the DataAnnotations attribute or the ValidationMessageFor() method.

In the sample code snippet below, we will demonstrate using the ErrorMessage parameter to display our own custom error message:

//Example: Custom error message in the Model
public class Activity
    public int Id {get; set;}
    [Required(ErrorMessage="Please enter an activity name")]
    public string ActivityName {get; set;}
    public int Status {get; set;}
Aside the ErrorMessage Parameter, we can specify a message as a second parameter in the ValidationMessage() method as illustrated in the code snippet below.

//Example: Custom error message
@model Activity  
@Html.Editor("ActivityName") <br/>
@Html.ValidationMessageFor(a => a.ActivityName, "Please enter an activity name.", new { @class = "text-danger" })

Inviting useful, relevant, well-written and unique guest posts