title: Client Side Validation on Nested models in ASP.Net MVC
body: <p>I'm trying to create a MVC model validation attribute that fills in the following situation:
  I have created several models (Birthday and PhoneNumber being excellant examples) that are submitted over multiple input fields on the view (month, day, year; areacode, exchange, suffix).</p>
  
  <pre><code>  public class PhoneNumber
    {
      [RegularExpression("^([2-9][0-8][0-9])$", ErrorMessage = "Invalid Area Code")]
      public virtual string AreaCode { get; set; }
  
      [RegularExpression("^([2-9][0-9][0-9])$", ErrorMessage = "Invalid Phone Exchange")]
      public virtual string Exchange { get; set; }
  
      [RegularExpression("^([0-9][0-9][0-9][0-9])$", ErrorMessage = "Invalid Phone Suffix")]
      public virtual string Suffix { get; set; }
    }
  </code></pre>
  
  <p>I often nest these models inside other models (Person has a PhoneNumber and a Birthday, for example). Sometimes, in my views, a PhoneNumber is required, and sometimes it isn't.
  I can handle these situations on the server side by using implementing the class as an IValidatableObject, but I run into trouble if I want to do client side validation, or even just do server side validation via attributes.</p>
  
  <p>I imagine I will have to build my own custom validation attribute but I'm not even sure where to start in accessing object and attribute information on multiple levels. Has anyone encountered anything like this? Any good ideas for pointing me in the right direction?</p>
  
  <p>Thanks in advance!</p>
  
  <p>--------Update------</p>
  
  <p>By using IClientValidatable, and GetClientValidationRules, I have access to the ModelMetadata can get the type of the container. The problem is that the container is birthday or phone number, not the type of the top level model, which is what is most important here. The ModelMetadata hasn't populated the Model property yet because one may not exist yet. What I'm really trying to do is get the type of the top level model. Anyone have any insight?</p>