Check if Validation Message Exists ASP.Net MVC 5

22,978

Solution 1

You can access the ModelState through a property of ViewData in order to check for validation errors before outputting any HTML:

 @if(!ViewData.ModelState.IsValid) {
      @Html.ValidationMessageFor(...)
 }

Edit: or, if you're wanting to check a specific property:

 @if(ViewData.ModelState["PropertyName"] != null && ViewData.ModelState["PropertyName"].Errors.Any()) {
       @Html.ValidationMessageFor(...)
  }

Solution 2

This is the span created by @ValidationMessagefor() :

<span class="field-validation-error" data-valmsg-for="FieldName" data-valmsg-replace="true"><span for="FieldName" generated="true" class="">Field name is required.</span></span>

You can just check class "field-validation-error" whether it exists or not.

Solution 3

This is a pretty dumb test, but usually sufficient, and has the added benefit of utilizing Intellisense in Visual Studio:

  1. Create Project/Helpers/HtmlHelper.cs as a new class

    using System.Web.Mvc;
    using System.Web.Mvc.Html;
    
    namespace Project.Helpers
    {
        public static class HtmlHelper
        {
            public static bool HasValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
            {
                var value = htmlHelper.ValidationMessageFor(expression).ToString();
    
                return value.Contains("field-validation-error");
            }
        }
    }
    
  2. Add that namespace to Views/Web.config:

    <configuration>
      <system.web.webPages.razor>
        <pages pageBaseType="System.Web.Mvc.WebViewPage">
          <namespaces>
            <add namespace="Project.Helpers" />
    
  3. Close and reopen the solution in Visual Studio, which I had to to for VS 2013 or Intellisense didn't pick up the new HTML helper in my Razor views

  4. Use it:

    @if (Html.HasValidationMessageFor(model => model.Property))
    {
        @* Do stuff *@
    }
    

Kartikeya's answer provided the markup generated by the Html.ValidatorMessageFor(...) method call:

<span class="field-validation-error" data-valmsg-for="FieldName" data-valmsg-replace="true">
    <span for="FieldName" generated="true" class="">
        Field name is required.
    </span>
</span>

(Code formatting, mine)

And as he said, testing for the field-validation-error class name should work fine.

Solution 4

a) unknown or general custom added error display (non model property specific)

  if (ViewData.ModelState.Any(x => x.Key == string.Empty))
  {
      @Html.ValidationSummary(true, string.Empty, new { @class = "error")
  }

b) model property specific error display

@Html.ValidationMessageFor(m => m.Email, string.Empty, new { @class = "error" })
Share:
22,978
knowledgeseeker
Author by

knowledgeseeker

Updated on July 22, 2022

Comments

  • knowledgeseeker
    knowledgeseeker almost 2 years

    Is there a way to check if Validation Message exists for a particualr field in ASP.Net MVC 5. I need to check this in Razaor form

    Currently is IsNullOrEmpty but i think ValidationMessage does return some html tags even if there are no validation errors ?

    I need to show a div only if a Validation Message Exists i.e. validation has failed for that for a particaulr field.

  • knowledgeseeker
    knowledgeseeker almost 10 years
    and the best way to do that?
  • Kartikeya Khosla
    Kartikeya Khosla almost 10 years
    @knowledgeseeker as per my knowledge the above answer is most suitable for your functionality because this is the html which ValidationMessageFor() will render in the DOM and this is the easiest way also..
  • Joseph Woodward
    Joseph Woodward over 8 years
    If the property key doesn't exist then you'll receive a NullReferenceException, so don't forget to check for null before trying to access the Errors property.