C.J.
C.J.

Reputation: 3527

ASP.NET Validator for multiple fields

This will be a two part questions:

  1. I have multiple textbox-es. All of them are required fields. How do I use ONE validator to validate ALL of the textboxes? (i.e. it will return error if any one of the textbox-es is empty)

  2. I have multiple textbox-es. AT LEAST one of them is/are required fields. How do I use ONE validator to validate such conditions? (i.e. it will return error if ALL of the textbox-es are empty, but will pass as long as one of this group of textbox-es has something in it.)

Upvotes: 2

Views: 6164

Answers (3)

astian
astian

Reputation: 684

I dont know of a way to do that, rather than create your own custom validation attribute. There are more than a few ways to achieve that, but the approach I would use is to assign the attribute to all included properties and then use reflection to check if at least one of them has a value (identifying them by checking if they have the attribute). In the IsValid method of the ValidationAttribute you have all the access to the instance and type so reflection should do the trick. Also, if you want client side validation to work, you can extend the IClientValidatable, send the values of all required fields through the GetClientValidationRules() rule parameters, and finally write your own javascript function to execute the rule. It sounds as an awful lot of work and it is, but if you make it flexible enough it should be reusable. Adding and removing the attribute to a property in a class should include/exclude a field from the validation list (if I may call it like that).

Here is where I got more familiar with that stuff when I had similar issues: Conditional Validation in ASP MVC

Upvotes: 0

freefaller
freefaller

Reputation: 19953

You need to use a Custom Validator (MSDN Link), as you will not be able to do what you want with the "single control" based validators.

This will allow you to write both client-side and server-side code, and respond accordingly.

It is very important that you implement server-side code, as client-side can easily be bypassed by somebody who knows what they're doing. Client-side is just a nice-to-have.

Upvotes: 5

Liath
Liath

Reputation: 10191

Set up a required field validator for each textbox and assign them to a validation group.You can use a ValidationSummary control to display all the results in a single list.

You can use a custom validator if you want to do your "one of these" logic. Unfortunately this will require you implement both the client side and server side validation code, there's no out the box validator.

Upvotes: 0

Related Questions