Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize Html.ValidationMessageFor in ASP MVC

Tags:

Is it possible to customize the Html.ValidationMessageFor method so that it produces different HTML?

I want to do something similar to:

<div class="field-error-box">     <div class="top"></div>     <div class="mid"><p>This field is required.</p></div> </div> 
like image 505
parleer Avatar asked Dec 05 '11 04:12

parleer


People also ask

How does ValidationMessageFor work in MVC?

ASP.NET MVC: ValidationMessageFor 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. Visit MSDN to know all the overloads of ValidationMessageFor() method.

What is custom validation in MVC?

This validation can be added for both the client side and the server side. You understand that decorating the properties in a model with an Attribute can make that property eligible for Validation. Some of the DataAnnotation used for validation are given below. Required. Specify a property as required.


1 Answers

I am not sure if it's possible to use paragraph instead of default span, as it may make impossible for validation plugin to place error messages. But for div -s, thats easy - you could write custom html helper.

Something along these lines (may need further testing/coding). You will need to include the namespace of this static extension method in your view, or put this into System.Web.Mvc.Html directly.

public static class Validator {     public static MvcHtmlString MyValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)     {         TagBuilder containerDivBuilder = new TagBuilder("div");         containerDivBuilder.AddCssClass("field-error-box");          TagBuilder topDivBuilder = new TagBuilder("div");         topDivBuilder.AddCssClass("top");          TagBuilder midDivBuilder = new TagBuilder("div");         midDivBuilder.AddCssClass("mid");         midDivBuilder.InnerHtml = helper.ValidationMessageFor(expression).ToString();          containerDivBuilder.InnerHtml += topDivBuilder.ToString(TagRenderMode.Normal);         containerDivBuilder.InnerHtml += midDivBuilder.ToString(TagRenderMode.Normal);          return MvcHtmlString.Create(containerDivBuilder.ToString(TagRenderMode.Normal));     } } 

As you see, this uses default ValidationMessageFor method, to not interfere with validation-plugin error message processing.

And you use this simply, as default validation message helper

@Html.MyValidationMessageFor(model => model.SomeRequiredField) 
like image 152
archil Avatar answered Nov 04 '22 08:11

archil