0

How do I check if a single property in my model has a validation error, from within my view?

I realise that I can do this, but it's not strongly typed so I'm concerned it's prone to errors:

@if (ViewData.ModelState["MyProperty"].Errors.Count() > 0)
{
    // Show validation error
}
Luke
  • 22,826
  • 31
  • 110
  • 193

1 Answers1

1

You can use something like this:

public static bool IsValidFor<TModel, TProperty>(this TModel model,
                                                 System.Linq.Expressions.Expression<Func<TModel, TProperty>> expression,
                                                 ModelStateDictionary modelState)
{
    string name = ExpressionHelper.GetExpressionText(expression);

    return modelState.IsValidField(name);
}

Usage:

if (!model.IsValidFor(x => x.MyProperty, ModelState)) 
{
    // Show validation error
}

Courtesy: this answer

Community
  • 1
  • 1
Mrchief
  • 75,126
  • 20
  • 142
  • 189
  • Thank you! I'm going to give this a go. When I know it's right I'll mark it correct. :) – Luke Oct 02 '14 at 15:15