size.go 689 B

123456789101112131415161718192021222324252627
  1. package validate
  2. // Validation error.
  3. var (
  4. ErrMustHaveMoreItems = NewError("must have at least %d items")
  5. ErrMustHaveFewerItems = NewError("must have no more than %d items")
  6. )
  7. // MaxSize validates the length of a slice as being less than or equal to a given maximum.
  8. func MaxSize[T any](l int) func([]T) error {
  9. return func(value []T) error {
  10. if len(value) > l {
  11. return ErrMustHaveFewerItems.With(l)
  12. }
  13. return nil
  14. }
  15. }
  16. // MinSize validates the length of a slice as being greater than or equal to a given minimum.
  17. func MinSize[T any](l int) func([]T) error {
  18. return func(value []T) error {
  19. if len(value) < l {
  20. return ErrMustHaveMoreItems.With(l)
  21. }
  22. return nil
  23. }
  24. }