I am just learning MVC and can't seem to figure out how to handle the following scenario, I have a form with a shipping address and a billing address. All fields are required. There is also a check box for "Billing Adress is same as shipping address". My problem is that the model state is never valid unless both addresses are completed. I could handle this fairly easily with some javascript that just added the values from the shipping address to the billing address fields but if there is a better way to handle this I would like to know. Any guide line on how this is commonly handled would be great. Thanks!
There are lots of ways to handle this. If you are not using client-side validation, then you can simply implement IValidatableObject on the model, and override the IsValid() method and do some code to check the validity of the model.
If you are using client-side validation, then you need a custom attribute, or use something like fluent validation.
You can accomplish this by creating a custom validation attribute:
http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3.aspx
The gist of it is that you create a new class based off ValidationAttribute
, and IClientValidatable
, override and implement as necessary, add your client-side validation (that you need anyhow), and apply the attribute to your optional field.
Or since the validation can be as complex as you want, apply it on a shared partly-optional, partly-required field.
That guy also has an alpha of a library he's writing to make MVC validation more flexible. Haven't used it myself, but you could give it a try.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With