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?
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
IClientValidatableinterface 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.