title: MVC3 Custom Validation error message doesn't display when using ViewModel
body: <p><strong>SUMMARY</strong></p>
  <p><code>Question:</code> Why doesn't the custom validation error message show when using a ViewModel.</p>
  <p><code>Answer:</code> The custom validation should be applied to the ViewModel not the Class.  See the end of @JaySilk84's answer for example code.</p>
  <p>MVC3, project using</p>
  <ul>
  <li>jquery-1.7.2.min.js</li>
  <li>modernizr-2.5.3.js</li>
  <li>jquery-ui-1.8.22.custom.min.js (generated by jQuery.com for the Accordion plugin)</li>
  <li>jquery.validate.min.js and</li>
  <li>jquery.validate.unobtrusive.min.js</li>
  </ul>
  <p>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.</p>
  <p>But with custom validation an error is generated in the code but the error message doesn't display.</p>
  <pre><code>public IEnumerable&lt;ValidationResult&gt; Validate(ValidationContext validationContext)
  { if (DOB &gt; DateTime.Now.AddYears(-18))
    { yield return new ValidationResult(&quot;Must be 18 or over.&quot;); }      }
  </code></pre>
  <p>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?</p>
  <p><strong>Update 1 :</strong></p>
  <p>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?</p>
  <p><strong>Update 2 :</strong></p>
  <p>I created a new MVC3 project with these two simple classes (Agency and Person).</p>
  <pre><code>  public class Agency : IValidatableObject
    {
  
      public int Id { get; set; }
  
      public string Name { get; set; }
  
      public DateTime DOB { get; set; }
  
      public IEnumerable&lt;ValidationResult&gt; Validate(ValidationContext validationContext)
      {
        if (DOB &gt; DateTime.Now.AddYears(-18)) { yield return new ValidationResult(&quot;Must be over 18.&quot;); }
      }
    }
  
    public class Person
    {
      public int Id { get; set; }
  
      public string Name { get; set; }
    }
  </code></pre>
  <p>Here's the Controller Code</p>
  <pre><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(&quot;Index&quot;);
        }
  
        return View(agency);
      }
      
      //[HttpPost]
      //public ActionResult Create(AgencyVM agencyVM)
      //{
      //  if (ModelState.IsValid)
      //  {
      //    var agency = agencyVM.Agency;
      //    db.Agencies.Add(agency);
      //    db.SaveChanges();
      //    return RedirectToAction(&quot;Index&quot;);
      //  }
  
      //  return View(agencyVM);
      //}
  </code></pre>
  <p>The View</p>
  <pre><code>@model CustValTest.Models.Agency
  @*@model CustValTest.Models.AgencyVM*@
  @* When using VM (model =&gt; model.Name)  becomes (model =&gt; model.Agency.Name) etc. *@
  
  @{
      ViewBag.Title = &quot;Create&quot;;
  }
  
  &lt;h2&gt;Create&lt;/h2&gt;
  
  &lt;script src=&quot;@Url.Content(&quot;~/Scripts/jquery.validate.min.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;@Url.Content(&quot;~/Scripts/jquery.validate.unobtrusive.min.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
  
  @using (Html.BeginForm()) {
      @Html.ValidationSummary(true)
      &lt;fieldset&gt;
          &lt;legend&gt;Agency&lt;/legend&gt;
  
          &lt;div class=&quot;editor-label&quot;&gt;
              @Html.LabelFor(model =&gt; model.Name)
          &lt;/div&gt;
          &lt;div class=&quot;editor-field&quot;&gt;
              @Html.EditorFor(model =&gt; model.Name)
              @Html.ValidationMessageFor(model =&gt; model.Name)
          &lt;/div&gt;
  
          &lt;div class=&quot;editor-label&quot;&gt;
              @Html.LabelFor(model =&gt; model.DOB)
          &lt;/div&gt;
          &lt;div class=&quot;editor-field&quot;&gt;
              @Html.EditorFor(model =&gt; model.DOB)
              @Html.ValidationMessageFor(model =&gt; model.DOB)
          &lt;/div&gt;
  
          &lt;p&gt;
              &lt;input type=&quot;submit&quot; value=&quot;Create&quot; /&gt;
          &lt;/p&gt;
      &lt;/fieldset&gt;
  }
  
  &lt;div&gt;
      @Html.ActionLink(&quot;Back to List&quot;, &quot;Index&quot;)
  &lt;/div&gt;
  </code></pre>
  <p>The ViewModel</p>
  <pre><code>  public class AgencyVM
    {
      public Agency Agency { get; set; }
  
      public Person Person { get; set; }
  
    }
  </code></pre>
  <p>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?</p>
  <p><strong>Update 3 :</strong></p>
  <p>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:</p>
  <pre><code>if (DOB &gt; DateTime.Now.AddYears(-18)) { yield return new ValidationResult(&quot;Must be over 18.&quot;, new [] { &quot;DOB&quot; }); }
  </code></pre>
  <p>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.</p>
  <pre><code>      ModelState.AddModelError(string.Empty, errMsgInvld);
        return View(agencyVM);
      }
      string errMsgInvld = &quot;There was an entry error, please review the entire form. Invalid entries will be noted in red.&quot;;
  </code></pre>
  <p>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)?</p>