Skip to content

Added Unique Tag #97

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: v2
Choose a base branch
from
Open
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
@@ -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
28 changes: 28 additions & 0 deletions builtins.go
Original file line number Diff line number Diff line change
@@ -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
@@ -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.
@@ -140,6 +142,7 @@ func NewValidator() *Validator {
"max": max,
"regexp": regex,
"nonnil": nonnil,
"unique": unique,
},
printJSON: false,
}