mirror of
https://github.com/kataras/iris.git
synced 2025-12-22 20:37:05 +00:00
Add new x/errors/validation package to make your life even more easier (using Generics)
This commit is contained in:
57
x/errors/validation/slice.go
Normal file
57
x/errors/validation/slice.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package validation
|
||||
|
||||
import "fmt"
|
||||
|
||||
type SliceValue[T any] interface {
|
||||
~[]T
|
||||
}
|
||||
|
||||
// SliceError describes a slice field validation error.
|
||||
type SliceError[T any, V SliceValue[T]] struct{ *FieldError[V] }
|
||||
|
||||
// Slice returns a new slice validation error.
|
||||
func Slice[T any, V SliceValue[T]](field string, value V) *SliceError[T, V] {
|
||||
return &SliceError[T, V]{Field(field, value)}
|
||||
}
|
||||
|
||||
// NotEmpty adds an error if the slice is empty.
|
||||
func (e *SliceError[T, V]) NotEmpty() *SliceError[T, V] {
|
||||
e.Func(NotEmptySlice)
|
||||
return e
|
||||
}
|
||||
|
||||
// Length adds an error if the slice length is not in the given range.
|
||||
func (e *SliceError[T, V]) Length(min, max int) *SliceError[T, V] {
|
||||
e.Func(SliceLength[T, V](min, max))
|
||||
return e
|
||||
}
|
||||
|
||||
// NotEmptySlice accepts any slice and returns a message if the value is empty.
|
||||
func NotEmptySlice[T any, V SliceValue[T]](s V) string {
|
||||
if len(s) == 0 {
|
||||
return "must not be empty"
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// SliceLength accepts any slice and returns a message if the length is not in the given range.
|
||||
func SliceLength[T any, V SliceValue[T]](min, max int) func(s V) string {
|
||||
return func(s V) string {
|
||||
n := len(s)
|
||||
|
||||
if min == max {
|
||||
if n != min {
|
||||
return fmt.Sprintf("must be %d elements", min)
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
if n < min || n > max {
|
||||
return fmt.Sprintf("must be between %d and %d elements", min, max)
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user