Handling nested struct in Go Validator.v2
Asked Answered
S

2

6

I have been using Go Validator.v2 for field validations and it works elegantly for my non-struct typed fields. However, when it comes to handling struct-based fields (within the original struct), there is no documentation about it whatsoever. https://pkg.go.dev/mod/gopkg.in/validator.v2

I know the v10 has support for it, but I prefer the built-in regex support in v2. Is there anyway I can customise validation for these struct-based fields? e.g.

type user struct {
   Name            string   `validate:"nonzero"`
   Age             int      `validate:"min=21"`
   BillingAddress  *Address  ???

}

I wish to validate the BillingAddress field as shown above, or do I simply write the validation tags in the Address model and it will automatically validate it, too?

Thanks and any pointers are appreciated!

Schreiber answered 20/10, 2020 at 9:2 Comment(0)
Z
0

The validator package will recursively search a struct. Just ensure that the nested struct's fields are not anonymous and have a validate tag.
If you find yourself ever lost on a package functionality, takes a look at their test files, it might reveal something. For example, the validator package testing has an example for nested structs here.

Example:

package main

import (
    "log"

    "gopkg.in/validator.v2"
)

type Address struct {
    Val string `validate:"nonzero"`
}

type User struct {
    Name           string `validate:"nonzero"`
    Age            int    `validate:"min=21"`
    BillingAddress *Address
}

func main() {
    nur := User{Name: "something", Age: 21, BillingAddress: &Address{Val: ""}}
    err := validator.Validate(&nur)
    log.Fatal(err)
}


2022/11/10 10:32:43 BillingAddress.Val: zero value
Zr answered 10/11, 2022 at 18:37 Comment(0)
M
-1

In the following example, we demonstrate how to validate nested structures in Go using the validator package.

type User struct { Name string Address Address validate:"required,dive" // 'dive' ensures nested validation }

type Address struct { City string validate:"required"
Street string validate:"required" }

Macdonald answered 1/11 at 10:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.