title: ASP.NET MVC model binding and validation question
body: <p>I'm trying to use MVC for a new project after having been around the block with all the samples and tutorials and such. However, I'm having a hard time figuring out where certain things should take place.</p>
  
  <p>As an example, I have an entity called Profile. This entity contains the normal profile type stuff along with a DateOfBirth property that is of type DateTime. On the HTML form, the date of birth field is split into 3 fields. Now, I know I can use a custom model binder to handle this, but what if the date entered is not a valid date? Should I be checking for that in the model binder? Should all my validation go in the model binder? Is it ok to have only a few things validated in the model binder and validate the rest in the controller or the model itself?</p>
  
  <p>Here's the code I have now, but it just doesn't look right to me. Seems dirty or smelly.</p>
  
  <pre><code>namespace WebSite.Models
  {
      public class ProfileModelBinder : IModelBinder
      {
          public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
          {
              DateTime birthDate;
  
              var form = controllerContext.HttpContext.Request.Form;
              var state = controllerContext.Controller.ViewData.ModelState;
  
              var profile = new Profile();
              profile.FirstName = form["FirstName"];
              profile.LastName = form["LastName"];
              profile.Address = form["Address"];
              profile.Address2 = form["Address2"];
              profile.City = form["City"];
              profile.State = form["State"];
              profile.Zip = form["Zip"];
              profile.Phone = form["Phone"];
              profile.Email = form["Email"];
              profile.Created = DateTime.UtcNow;
              profile.IpAddress = controllerContext.HttpContext.Request.UserHostAddress;
  
              var dateTemp = string.Format("{0}/{1}/{2}",
                  form["BirthMonth"], form["BirthDay"], form["BirthYear"]);
  
              if (string.IsNullOrEmpty(dateTemp))
                  state.AddModelError("BirthDate", "Required");
              else if (!DateTime.TryParse(dateTemp, out birthDate))
                  state.AddModelError("BirthDate", "Invalid");
              else
                  profile.BirthDate = birthDate;
  
              return profile;
          }        
      }
  }
  </code></pre>
  
  <p>Building on the sample code above, how would you do the validation message for a 3 part field? In the case above, I'm using a completely separate key that doesn't actually correspond to a field in the form, because I don't want an error message to appear beside all 3 fields. I only want it to appear to the right of the Year field.</p>