Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle conditional validation in MVC3?

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!

like image 202
Mike Avatar asked Nov 06 '11 22:11

Mike


2 Answers

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.

like image 196
Erik Funkenbusch Avatar answered Oct 20 '22 15:10

Erik Funkenbusch


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.

like image 44
Merlyn Morgan-Graham Avatar answered Oct 20 '22 17:10

Merlyn Morgan-Graham