浏览代码

add slice size validation

Aneurin Barker Snook 1 年之前
父节点
当前提交
f929f4ffff
共有 1 个文件被更改,包括 31 次插入0 次删除
  1. 31 0
      size.go

+ 31 - 0
size.go

@@ -0,0 +1,31 @@
+package validate
+
+import (
+	"errors"
+)
+
+// Validation error.
+var (
+	ErrTooFewItems  = errors.New("too few items")
+	ErrTooManyItems = errors.New("too many items")
+)
+
+// MaxSize validates the length of a slice as being less than or equal to a given maximum.
+func MaxSize[T any](l int) func([]T) error {
+	return func(value []T) error {
+		if len(value) > l {
+			return ErrTooFewItems
+		}
+		return nil
+	}
+}
+
+// MinSize validates the length of a slice as being greater than or equal to a given minimum.
+func MinSize[T any](l int) func([]T) error {
+	return func(value []T) error {
+		if len(value) < l {
+			return ErrTooManyItems
+		}
+		return nil
+	}
+}