Frage

SUMMARY

Question: Why doesn't the custom validation error message show when using a ViewModel.

Answer: The custom validation should be applied to the ViewModel not the Class. See the end of @JaySilk84's answer for example code.

MVC3, project using

  • jquery-1.7.2.min.js
  • modernizr-2.5.3.js
  • jquery-ui-1.8.22.custom.min.js (generated by jQuery.com for the Accordion plugin)
  • jquery.validate.min.js and
  • jquery.validate.unobtrusive.min.js

I have validation working in my project for both dataannotations in the View and for ModelState.AddModelError in the Controller so I know I have all the validation code configured properly.

But with custom validation an error is generated in the code but the error message doesn't display.

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{ if (DOB > DateTime.Now.AddYears(-18))
  { yield return new ValidationResult("Must be 18 or over."); }      }

Drilling down in debug in the POST action the custom validation causes Model state to fail and the error message is placed in the proper value field but when the model is sent back to the view the error message doesn't display. In the controller I also have ModelState.AddModelError code and its message does display. How is that handled differently as to one would work and not the other? If not that what else would prevent the error message from displaying?

Update 1 :

I'm using a ViewModel to create the model in the view. I stripped out the ViewModel and the error message started displaying, as soon I added the ViewModel back in the message again stopped displaying. Has anyone successfully used a custom validation with a ViewModel? Was there anything you had to do extra to get it to work?

Update 2 :

I created a new MVC3 project with these two simple classes (Agency and Person).

  public class Agency : IValidatableObject
  {

    public int Id { get; set; }

    public string Name { get; set; }

    public DateTime DOB { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
      if (DOB > DateTime.Now.AddYears(-18)) { yield return new ValidationResult("Must be over 18."); }
    }
  }

  public class Person
  {
    public int Id { get; set; }

    public string Name { get; set; }
  }

Here's the Controller Code

    public ActionResult Create()
    {
        return View();
    } 

    //
    // POST: /Agency/Create

    [HttpPost]
    public ActionResult Create(Agency agency)
    {
      if (ModelState.IsValid)
      {

        db.Agencies.Add(agency);
        db.SaveChanges();
        return RedirectToAction("Index");
      }

      return View(agency);
    }
    
    //[HttpPost]
    //public ActionResult Create(AgencyVM agencyVM)
    //{
    //  if (ModelState.IsValid)
    //  {
    //    var agency = agencyVM.Agency;
    //    db.Agencies.Add(agency);
    //    db.SaveChanges();
    //    return RedirectToAction("Index");
    //  }

    //  return View(agencyVM);
    //}

The View

@model CustValTest.Models.Agency
@*@model CustValTest.Models.AgencyVM*@
@* When using VM (model => model.Name)  becomes (model => model.Agency.Name) etc. *@

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Agency</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.DOB)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.DOB)
            @Html.ValidationMessageFor(model => model.DOB)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

The ViewModel

  public class AgencyVM
  {
    public Agency Agency { get; set; }

    public Person Person { get; set; }

  }

When just Agency is presented in the View the validation error displays (DOB under 18). When the ViewModel is presented the error doesn't display. The custom validation always catches the error though and causes ModelState.IsValid to fail and the view to be re-presented. Can anyone replicate this? Any ideas on why and how to fix?

Update 3 :

As a temporary work around I have changed the Validation into a field level one (vs. a model level one) by adding a parameter to the ValidationResult:

if (DOB > DateTime.Now.AddYears(-18)) { yield return new ValidationResult("Must be over 18.", new [] { "DOB" }); }

The problem with this is now the error message is showing up next to the field rather than at the top of the form (which is not good in say an accordion view since the user will be returned to the form with no visible error message). To fix this secondary problem I added this code to the Controller POST action.

      ModelState.AddModelError(string.Empty, errMsgInvld);
      return View(agencyVM);
    }
    string errMsgInvld = "There was an entry error, please review the entire form. Invalid entries will be noted in red.";

The question is still unanswered, why doesn't the model level error message show with a ViewModel (see my response to JaySilk84 for more on this)?

War es hilfreich?

Lösung

The issue is now that your models are nested, the error message is being placed into ModelState under Agency without the .DOB because you didn't specify it in the ValidationResult. The ValidationMessageFor() helper is looking for a key named Agency.DOB (see relevant code below from ValidationMessageFor() helper):

string fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expression);
FormContext clientValidation = htmlHelper.ViewContext.GetFormContextForClientValidation();
if (!htmlHelper.ViewData.ModelState.ContainsKey(fullHtmlFieldName) && clientValidation == null)
    return (MvcHtmlString) null;

GetFullHtmlFieldName() is returning Agency.DOB, not Agency

I think if you add the DOB to the ValidationResult it will work:

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    if (DOB > DateTime.Now.AddYears(-18)) { yield return new ValidationResult("Must be over 18.", new List<string>() { "DOB" }); }
}

That second parameter to ValidationResult will tell it what key to use in ModelState (By default it will append the parent object which is Agency) so the ModelState will have a key named Agency.DOB which is what your ValidationMessageFor() is looking for.

Edit:

If you don't want field level validation then you don't need the Html.ValidationMessageFor(). You just need the ValidationSummary().

The view is treating AgencyVM as the model. If you want it to validate properly then put the validation at the AgencyVM level and have it validate the child objects. Alternatively you could put validation on the child objects but the parent object (AgencyVM) has to aggregate it to the view. Another thing you can do is keep it as it is and change ValidationSummary(true) to ValidationSummary(false). This will print everything in ModelState to the summary. I think removing the validation from Agency and putting it on AgencyVM might be the best approach:

 public class AgencyVM : IValidatableObject

    {
        public Agency Agency { get; set; }

        public Person Person { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (Agency.DOB > DateTime.Now.AddYears(-18)) { yield return new ValidationResult("Must be over 18."); }
            if (string.IsNullOrEmpty(Agency.Name)) { yield return new ValidationResult("Need a name"); }
        }
    }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top