go-playground / validator

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
MIT License
16.41k stars 1.3k forks source link

Custom validation on slice of embedded structs #1111

Open davidterranova opened 1 year ago

davidterranova commented 1 year ago

Package version eg. v9, v10:

v10

Issue, Question or Enhancement:

Hello, I am unable to get a custom validator to work on a slice of embedded structs

Code sample, to showcase or reproduce:

package main

import (
    "fmt"

    "github.com/go-playground/validator/v10"
)

type Test struct {
    Actors []Actor `validate:"required"`
}

type Actor struct {
    Role Role   `validate:"required,role_validation"`
    Name string `validate:"required"`
}

func main() {
    validator := validator.New()
    err := validator.RegisterValidation("role_validation", RoleValidator)
    if err != nil {
        panic(err)
    }

    test := Test{
        Actors: []Actor{
            {
                Role: "RoleRequestor",
                Name: "John",
            },
        },
    }
    err = validator.Struct(test)

    // we should have an error but we don't
    fmt.Println("err: ", err)
}

type Role string

func RoleValidator(fl validator.FieldLevel) bool {
    return false
}
subsandwich commented 1 year ago

Hi @davidterranova, you should be able to resolve this issue by changing the Actors tag to validate:"required,dive"

See docs: https://pkg.go.dev/github.com/go-playground/validator/v10#hdr-Dive