ValidationMessageFor HTML Helper in MVC3 Razor

  • Html.ValidationMessageFor helper is used to display validation errors or messages.
  • When there is an error for a particluar field in the ModelState dictionary, we can use the ValidationMessageFor helper to display the message.
  • This helper renders the message inside span element and gives the text red color.
  • ValidationMessageFor Helper binds the control to the model. It helps in model binding.

It has following overloads :

Overload 1 :


This overload accepts linq expression which binds it to the model property.

Syntax :

    @Html.ValidationMessageFor(m => m.FirstName)

In the above overload, we are binding the helper with the FirstName model property. In this case we are not specifying any error message. It will display the error message from the model, where model property is defined.



This is the model property. We have applied DataAnnotation attributes to the property. If the FirstName field is left blank and form is submitted, then it will through an error. The error message is the one mentioned as parameter to the Required attribute.


UI :


We submitted the form with FirstName left blank. The validation failed and error is displayed.

Rendered HTML :



    <span class="field-validation-error" data-valmsg-for="FirstName" data-valmsg-replace="true">First Name is mandatory Field!</span>


Overload 2 :



This overload accepts a linq expression and a validation message to display on UI when validation fails.


Syntax :

    @Html.ValidationMessageFor(m => m.FirstName,"FirstName is manadatory property!!")

Here we are passing the validation message as well. If we do not want to specify the validation message at model level, then we can specify at control level.

UI :



Rendered HTML :

    <span class="field-validation-error" data-valmsg-for="FirstName" data-valmsg-replace="true">FirstName is manadatory property!!</span>


Overload 3 :



This overload is similar to previous one, but accepts one extra parameter i.e. htmlAttributes object.


Syntax :

    @Html.ValidationMessageFor(m => m.FirstName, "FirstName is manadatory property!!", new {@class = "validationText"})


UI :



Rendered HTML :

    <span class="field-validation-error validationText" data-valmsg-for="FirstName" data-valmsg-replace="false">FirstName is manadatory property!!</span>


Overload 4 :



This overload accepts IDictionary object of htmlAttributes.

Syntax :

    @Html.ValidationMessageFor(m => m.FirstName, "FirstName is manadatory property!!", attributes)



UI :


Rendered HTML :


    <span class="field-validation-error validationText" data-valmsg-for="FirstName" data-valmsg-replace="false" style="font-style:italic">FirstName is manadatory property!!</span>

0 comments:

Post a Comment