2

How can I validate a slice of structs using validator framework?

For example, in the following type definitions, I want to validate each element in the field Puppies.

type User struct {
    FirstName string `json:"fname" validate:"alpha"`
    LastName  string `json:"lname" validate:"alpha"`
    Email     string `json:"email" validate:"required,email"`
    Puppies   []*Dog `json:"puppies"`
    // Puppy *Dog
}

type Dog struct {
    PuppyName string `json:"puppyname" validate:"alpha"`
}

https://play.golang.org/p/9-1Ih76hD7j is not working with array of dogs.

https://play.golang.org/p/PGQT3jaFVuS is working - with only one dog.

I want to validate the slice of structs, can we do it using goplayground validator framework?

blackgreen
  • 34,072
  • 23
  • 111
  • 129
Rajesh
  • 61
  • 1
  • 2
  • 5

1 Answers1

6

Use dive tag to perform validations on iterable structures:

Puppies   []*Dog `json:"puppies" validate:"dive"`

Refer to https://godoc.org/github.com/go-playground/validator#hdr-Dive

Iblisto
  • 309
  • 2
  • 7
  • I tried with dive tag. It is working. ok so for slice, array, map I need to use dive tag. Thank you so much @lblisto – Rajesh Nov 28 '20 at 03:18