0

I want to make custom @Html.ValidationMessageFor.

I have this code, but it uses @Html.ValidationMessageFor, and now brings the HTML formatted, and only want the return of the errors.

How to do this?

My code:

public static MvcHtmlString MyValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
    {
        return MvcHtmlString.Create(helper.ValidationMessageFor(expression).ToString());
    }
Kyle Trauberman
  • 25,414
  • 13
  • 85
  • 121
Tiedt Tech
  • 719
  • 15
  • 46

3 Answers3

2

You can do a lot of this from DataAnnotations. What are you validating? For instance, if it's Required, you can have

[Required(ErrorMessage= "Please enter something, anything, PLEASE!!!! Come on, I've been nice, just do it! DON'T LEAVE ME EMPTY FOR THE LOVE OF GOD")]
public string MyValue

Edited for more dramatic effect.

Whoops! I read this way wrong, you just want the message, you could try this:

public static T GetAttributeFrom<T>(this object instance, string propertyName) where T : Attribute
{
    var attrType = typeof(T);
    var property = instance.GetType().GetProperty(propertyName);
    return (T)property .GetCustomAttributes(attrType, false).First();
}


var RequiredMessage = player.GetAttributeFrom<RequiredAttribute>("MyValue").ErrorMessage;

Source: How to retrieve Data Annotations from code? (programmatically)

Community
  • 1
  • 1
Chad Kapatch
  • 585
  • 1
  • 4
  • 16
0

I found an excellent source that demystifies writing custom validators. The information is too much to post here, so follow this link: http://tdryan.blogspot.com/2010/12/aspnet-mvc-3-custom-validation.html

This got me going, and I have written many validators based on this tutorial.

Good luck.

JamieMeyer
  • 386
  • 3
  • 14
0

I use the following code to get all error messages:

StringBuilder sb = new StringBuilder();
foreach (ModelState state in ModelState.Values)
    foreach (ModelError error in state.Errors)
        sb.AppendFormat("<div>{0}</div>", error.ErrorMessage);

You can change this code with little effort to get only error messages for the control you want.

Retired_User
  • 1,595
  • 11
  • 17