If I have a search object with a list of fields, can I, using the System.ComponentModel.DataAnnotations namespace, set it up to validate that at least one of the fields in the search is not null or empty? i.e All the fields are optional but at least one should always be entered.
Share
I’d create a custom validator for this – it won’t give you client side validation, just server side.
Note that for this to work, you’ll need to be using
nullabletypes, as value types will default to0orfalse:First create a new validator:
You can then decorate your models with this:
Then when you call
ModelState.IsValidyour validator will be called, and your message will be added to the ValidationSummary on your view.Note that you could extend this to check for the type of property coming back, or look for attributes on them to include/exclude from validation if you want to – this is assuming a generic validator that doesn’t know anything about the type it’s validating.