Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,9 @@ regexp

nonnil
Validates that the given value is not nil. (Usage: nonnil)

unique
Validates that the given values of an array or slice are unique. (Usage: unique)
```

Custom validators
Expand Down
28 changes: 28 additions & 0 deletions builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,3 +287,31 @@ func nonnil(v interface{}, param string) error {
}
return nil
}

// unique validates uniqueness of elements of an array
func unique(v interface{}, _ string) error {
arr := reflect.ValueOf(v)
if arr.Kind() == reflect.Ptr {
if arr.IsNil() {
return nil
}
arr = arr.Elem()
}
switch arr.Kind() {
case reflect.Slice, reflect.Array:
m := make(map[interface{}]bool)
for i := 0; i < arr.Len(); i++ {
val := arr.Index(i).Interface()
_, exists := m[val]
if exists {
return ErrRepeating
}

m[val] = true
}
default:
return ErrUnsupported
}

return nil
}
3 changes: 3 additions & 0 deletions validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ var (
ErrInvalid = TextErr{errors.New("invalid value")}
// ErrCannotValidate is the error returned when a struct is unexported
ErrCannotValidate = TextErr{errors.New("cannot validate unexported struct")}
// ErrRepeating is the error returned when the elements are not unique
ErrRepeating = TextErr{errors.New("repeating value found")}
)

// ErrorMap is a map which contains all errors from validating a struct.
Expand Down Expand Up @@ -140,6 +142,7 @@ func NewValidator() *Validator {
"max": max,
"regexp": regex,
"nonnil": nonnil,
"unique": unique,
},
printJSON: false,
}
Expand Down