Monthly Archives: March 2015

Custom MVC Validation Message

The MVC has a commonly used extension method @Html.ValidationMessageFor(model =>model.Property), that generates a code similar to

<span class="field-validation-error" data-valmsg-replace="true" data-valmsg-for="Name">
  The Name field is required.
</span>

We wanted to hide the error message into a tooltip of a red asterisk (yes, I know that it is not user/mobile  friendly). Something like this:

ScreenShot

We have @Html.EditorFor(), so perhaps there will be an easy way…. Nope, there isn’t. We have to do some work either through JavaScript and CSS or by creating a separate helper.

Javascript & CSS way

This is easier way and it works.

C# way

Changing the generated markup to something to something like

<span data-error-message="Error message" class="field-validation-error">*</span>

would work too.

Well, it seems that there is no easy way to get a validation error message for a specified property of a model. The code bubbles through several recalls and ends up in a method ValidationMessageHelper in a file ValidationExtensions.cs.

I can change either tag or css class for generated element, I can of course add another attributes through htmlAttributes dictionary, but that is about it. I can’t get the message itself (unless I do the work myself).

I have found some nice info about how to generate custom summary and someone who needed to create a custom generated validation message with an icon (using @Html.ValidationIconFor(model => model.property)). It is a considerable amount of basically cope and paste code.

Conclusion

AFACT there is no easy way to have a template or something similar for validation message. As long as the screen estate is not an issue, try to stick with default.