0

This question has been asked many times here on StackOverflow, but I don't see anything that addresses my need. I want to drive the client side, i.e. jQuery, validation to be conditional by using a server side data annotation.

That is, I am trying to build a generic drop down model where if the user chooses 'Other' from a DropDownList, a coupled text field called Other is then mandatory. How can I do this using an attribute on the dropdown model property?

Gaz Winter
  • 2,924
  • 2
  • 25
  • 47
ProfK
  • 49,207
  • 121
  • 399
  • 775

2 Answers2

0

Yes, this is possible. Take a look at the MVC Foolproof framework which has many nice additions such as [RequiredIf] validation attributes. They also work with client side validation.

If you are interested in the specifics of how to implement this you could take a look at the source code of those attributes. It's quite a lot of work though. You need to have your attributes override the IClientValidatable interface and then write custom unobtrusive adapters on the client side.

I wrote an example of such implementation here. It's not dealing with conditional validation but the technique is exactly the same. You just need to adapt the client side adapter to your needs.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Darin, you always answer my questions so well. I'm already giving Foolproof a shot, thanks. If it works like I want, I'll event put a bounty on this just to give you points. Thanks! – ProfK Jan 03 '13 at 12:18
0

There are many RequiredIf implementations around, such as the one below:

http://blogs.msdn.com/b/stuartleeks/archive/2011/10/06/flexible-conditional-validation-with-asp-net-mvc-3.aspx

Another option is FluentValidation, which is not an attribute based validation, but very flexible.

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291