Search code examples
asp.netasp.net-mvcvalidation

MVC - Mark Multiple Fields invalid in Custom Validation Attribute


I have a form where users enter their preferred contact method. It has: - a radio button where a user selects whether they'd like to be contact by phone or email or either - a textbox for the user's email address - a textbox for the user's phone number

I have validation via a custom attribute that verifies that if the user selected phone they entered a phone number, if they selected email they entered an email, etc... but it's at a class level on my ViewModel. As such the validation doesn't mark the expected field as invalid.

Is there a way that my IsValid override (or some other method) can mark the child property's value as invalid so I get highlighting?


Solution

  • If you are using .NET 4.0 you may take a look at the following blog post. If not what can I say other than, well, Data Annotation have limits. And it's exactly because of limitations like this (of course that's just an example but there are many others) that I use FluentValidation.NET.