开发者

Validate a Collection Has at Least One Item using Validation Application Block

开发者 https://www.devze.com 2022-12-09 05:14 出处:网络
Using the Enterprise Library 4.1 Validation Application Block, how can I validate that a collection proper开发者_开发知识库ty contains at least one item?I\'m assuming you mean out of the box.If so, th

Using the Enterprise Library 4.1 Validation Application Block, how can I validate that a collection proper开发者_开发知识库ty contains at least one item?


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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号