Ponni
Ponni

Reputation: 453

Data annotation validation for multiple model properties

I'm currently using MVC data annotations for validating my form and it looks quite easy.

Now, I have a particular situation:

IF(checkbox1value = checked), then validate if textbox is not empty. If textbox is empty, then show validation error message.

How do I do this? Both checkbox and textbox are available as my model properties (bool and string respectively).

Is it possible to do this via a custom validation?

Upvotes: 1

Views: 1655

Answers (2)

Fran
Fran

Reputation: 6520

You can use a custom validator or IValidateableOject

There's a good explanation of both options here.

From the link. If you need to support client validation, then a custom validator is what you want.

If your validation is strictly server side and you want to validate a number of business rules at once then use IValidateableObject.

Upvotes: 3

Brian Mains
Brian Mains

Reputation: 50728

I had to switch to Foolproof validation, which offered this functionality through it's RequiredIfTrue validator. I also really liked Fluent Validation since it was really flexible, and would also easily offer this functionality. Foolproof client-side support is provided for each of it's validators, where the boundary between client and server validation with Fluent Validation is not as easily distinguishable.

Upvotes: 0

Related Questions