简体   繁体   中英

validating array of structs using goplayground validator library

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM