title: ASP.NET MVC3 Conditional Validation of nested model for EditorTemplate
body: <p>Suppose you have a viewModel:</p>
  
  <pre><code>public class CreatePersonViewModel
  {
      [Required]
      public bool HasDeliveryAddress {get;set;}
  
      // Should only be validated when HasDeliveryAddress is true
      [RequiredIf("HasDeliveryAddress", true)]
      public Address Address { get; set; }
  }
  </code></pre>
  
  <p>And the model <code>Address</code> will look like this:</p>
  
  <pre><code>public class Address : IValidatableObject
  {
      [Required]
      public string City { get; set; }
      [Required]        
      public string HouseNr { get; set; }
      [Required]
      public string CountryCode { get; set; }
      [Required]
      public string FirstName { get; set; }
      [Required]
      public string LastName { get; set; }
      [Required]
      public string ZipCode { get; set; }
      [Required]
      public string Street { get; set; }
  
      #region IValidatableObject Members
  
      public IEnumerable&lt;ValidationResult&gt; Validate(ValidationContext validationContext)
      {
          string[] requiredFields;
          var results = new List&lt;ValidationResult&gt;();
  
          // some custom validations here (I removed them to keep it simple)
  
          return results;
      }
  
      #endregion
  }
  </code></pre>
  
  <p>Some would suggest to create a viewmodel for Address and add some custom logic there but I need an instance of <code>Address</code> to pass to my EditorTemplate for Address.</p>
  
  <p>The main problem here is that the validation of Address is done before the validation of my PersonViewModel so I can't prevent it.</p>
  
  <p><em>Note: the RequiredIfAttribute is a custom attribute which does just what I want for simple types.</em> </p>