title: Selective validation in MVC3
body: <p>I have an address class like so:</p>
  
  <pre><code>public class CustomerAddress
  {
      [Required]
      public string Line1 { get; set; }
  
      public string Line2 { get; set; }
  
      [Required]
      public string Town { get; set; }
  
      [Required]
      public string Postcode { get; set; }
  }
  </code></pre>
  
  <p>And I have a  view model like so:</p>
  
  <pre><code>public class CheckoutViewModel
  {
      [Required]
      public string Name { get; set; }
  
      //... etc
  
      public bool DeliverySameAsBilling { get; set; }
  
      public CustomerAddress BillingAddress { get; set; }
  
      public CustomerAddress DeliveryAddress { get; set; }
   }
  </code></pre>
  
  <p>I only want the delivery address to validate when <code>DeliverySameAsBilling</code> is false, and I can see from <a href="http://www.squarewidget.com/post/2011/06/Class-Level-Validation-in-MVC-3-with-IValidatableObject.aspx" rel="nofollow noreferrer">this</a> that IValidatableObject might be the way to go.</p>
  
  <p>That example imposes more strict criteria on the model than the attributes do though; in my case I want to optionally ignore the <code>[Required]</code> attributes in the <code>CustomerAddress</code> class.  How do I do this?  How would I wire up the appropriate client side validation?</p>
  
  <p>Alternatively I could use a custom attribute like <a href="https://stackoverflow.com/questions/5816313/mvc3-unobtrusive-validation-group-of-inputs">this</a> on each of <code>BillingAddress</code> and <code>DeliveryAddress</code> and then maybe the client side validation would be more easily handled; however I still don't know how to effectively "cancel" the validation for the property if <code>DeliverySameAsBilling</code> is true.</p>
  
  <p>Which is best?</p>