How to avoid duplicate elements in slice in json validation?

966 views Asked by At

Although I am not a pro-Golang developer, I am trying to restrict the duplicate elements from my array in struct during JSON validation.

type Test struct {
Test []*string `json:"test" validate:"required,min=1,max=10,excludes=duplicate"`
}

I am using excludes parameter but it's not working for me.

2

There are 2 answers

0
ryuk On

For array & slices you should use the unique tag.

type Test struct {
    Test []*string `json:"test" validate:"required,min=1,max=10,unique"`
}

Checking the docs:

For arrays & slices, unique will ensure that there are no duplicates

https://pkg.go.dev/github.com/go-playground/validator#hdr-Unique

0
Zamicol On

There's this issue: https://github.com/golang/go/issues/48298

Which will add a JSON "DisallowDuplicateFields" to the Go standard library.