Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8307239
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T18:29:14+00:00 2026-06-08T18:29:14+00:00

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

  • 0

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)?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T18:29:15+00:00Added an answer on June 8, 2026 at 6:29 pm

    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"); }
            }
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Question: Why does my .gif load, but not play when updating using GifSourcePropertyChanged ?
Summary of my question: Does NSURLConnection retain its delegate? Detailed question and scenario: I
Clarification/summary for the question -- we're looking for: a hosted bug tracking system, that
A short summary of the question: I have a parent class which is extended
Title edits that reflect a better summary of the question are welcome. I'd like
Summary Below is the full question (a bit complicated in its full form) here's
EDIT: In case the question below looks a bit 'extensive', the summary is that
Why doesn't this work? Route: routes.MapRoute( Summary, {controller}/{id}, new { controller = Summary, action
In summary, I think my question is this: How can I force hxcpp to
Summary I'm a seasoned programmer with years of experience in Windows Forms development using

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.