Question

Using the Enterprise Library 4.1 Validation Application Block, how can I validate that a collection property contains at least one item?

Was it helpful?

Solution

I'm assuming you mean out of the box. If so, then I don't think there is way to validate directly the number of items in a collection.

These are some other ways that you could try:

  1. Decree that you only deal with null collections and not empty collections and use a Not Null Validator. Not practical, though.

  2. Use self validation and have the object validate in code that the collection(s) have the correct number of items. Will work but it's nice to have the validation in the configuration file.

  3. Expose the collection count as a property. This could be done, assuming an employee collection for example, with an EmployeeCount property on your object that contains the collection or you could create your own custom collections that expose a count property. Then you could use a Range Validator to validate on the Count property.

  4. Create a custom validator that can validate the number of items in a collection -- something like CollectionCountRangeValidator.


If I wanted to develop something quickly, I would probably go with option 3. However, option 4 fits in well with the Enterprise Library approach and also allows your class design to be independent of the validation requirements. Plus you could always reuse it on your next project. :) And does anyone really miss creating their own collections when a List will do nicely?

OTHER TIPS

This is already implemented in the EntLib Contrib. This is called CollectionCountValidator.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top