Skip to content

Commit

Permalink
feat(unique): Add support for struct memember validation (#1048)
Browse files Browse the repository at this point in the history
This allows validating that two struct memebers are unique. This has
been documented as a feature, but has never been actually implemented.
  • Loading branch information
zemzale committed Mar 19, 2023
1 parent cc768b1 commit 1c1f70d
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
13 changes: 13 additions & 0 deletions baked_in.go
Expand Up @@ -335,6 +335,19 @@ func isUnique(fl FieldLevel) bool {

return field.Len() == m.Len()
default:
if parent := fl.Parent(); parent.Kind() == reflect.Struct {
uniqueField := parent.FieldByName(param)
if uniqueField == reflect.ValueOf(nil) {
panic(fmt.Sprintf("Bad field name provided %s", param))
}

if uniqueField.Kind() != field.Kind() {
panic(fmt.Sprintf("Bad field type %T:%T", field.Interface(), uniqueField.Interface()))
}

return field.Interface() != uniqueField.Interface()
}

panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}
}
Expand Down
35 changes: 35 additions & 0 deletions validator_test.go
Expand Up @@ -9991,6 +9991,41 @@ func TestUniqueValidation(t *testing.T) {
}
}
PanicMatches(t, func() { _ = validate.Var(1.0, "unique") }, "Bad field type float64")

t.Run("struct", func(t *testing.T) {
tests := []struct {
param interface{}
expected bool
}{
{struct {
A string `validate:"unique=B"`
B string
}{A: "abc", B: "bcd"}, true},
{struct {
A string `validate:"unique=B"`
B string
}{A: "abc", B: "abc"}, false},
}
validate := New()

for i, test := range tests {
errs := validate.Struct(test.param)
if test.expected {
if !IsEqual(errs, nil) {
t.Fatalf("Index: %d unique failed Error: %v", i, errs)
}
} else {
if IsEqual(errs, nil) {
t.Fatalf("Index: %d unique failed Error: %v", i, errs)
} else {
val := getError(errs, "A", "A")
if val.Tag() != "unique" {
t.Fatalf("Index: %d unique failed Error: %v", i, errs)
}
}
}
}
})
}

func TestUniqueValidationStructSlice(t *testing.T) {
Expand Down

0 comments on commit 1c1f70d

Please sign in to comment.