Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Validation Message Exists ASP.Net MVC 5

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.

like image 803
knowledgeseeker Avatar asked Jul 29 '14 16:07

knowledgeseeker


People also ask

How to display validationmessagefor in MVC?

ValidationMessageFor is in-built for each Html control in MVC, whatever ErrorMessage specified in the model, that will appear on screen as validation message. You can display all validation message together or each message on field itself. Here is an example how you can display the validation message exactly above the field.

How to validate form without student name in ASP NET MVC?

Now, when the user submits a form without entering a StudentName then ASP.NET MVC uses the data- attribute of HTML5 for the validation and the default validation message will be injected when validation error occurs, as shown below. The error message will appear as the image shown below.

How to do client side validation in ASP NET MVC 5?

For client side validation we will use jquery validation library that comes when we create a new ASP.Net MVC 5 Application. Expand App_Start Folder in Solution and Open BundleConfig.

How to check if field validation error exists or not?

You can just check class "field-validation-error" whether it exists or not. Show activity on this post. This is a pretty dumb test, but usually sufficient, and has the added benefit of utilizing Intellisense in Visual Studio:


4 Answers

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(...)
  }
like image 59
Ben Griffiths Avatar answered Sep 23 '22 14:09

Ben Griffiths


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.

like image 45
Kartikeya Khosla Avatar answered Sep 20 '22 14:09

Kartikeya Khosla


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.

like image 39
Greg Burghardt Avatar answered Sep 24 '22 14:09

Greg Burghardt


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" })
like image 35
Mark Macneil Bikeio Avatar answered Sep 23 '22 14:09

Mark Macneil Bikeio