views:

175

answers:

1

How can I implement selective client side validation
using MVC 2 built-in validation system?
Assume I have a checkbox in my form title "Do you have any child?"
and if checked the textbox below it should be required
(textbox titled Number of children).

A: 

A few options that might get you thinking here. In the case of multiple post actions (e.g. clicking cancel button on a form shouldn't fire validation) I have made sure that forms only post one actions and anything else is essentially a styled link. Validation won't fire in this case.

If, as is in your case, you have complex validation I would suggest creating a custom validator and registering a client side adapter e.g.

[RequiredIfHasChildren]

So you'd be writing a custom validation attribute, a custom model validator and some JavaScript code to register a new client side validator. This sort of approach has worked for me in the past but the dependency on another model property can be a bit of a problem.

Hopefully this helps.

kouPhax