Skip to content

StructLevel.Parent() not return real parent #715

@Torwang1

Description

@Torwang1

Package version eg. v9, v10:

V10

Issue, Question or Enhancement:

validator.StructLevel.Parent() not return real parent, when the struct is nested.

type (
	// User ...
	User struct {
		Name    string
		Address Address `validate:"structonly"`
	}

	// Address ...
	Address struct {
		Street string
	}
)

validator.StructLevel.Parent() on nested Address:
expect: User
but: Address

Code sample, to showcase or reproduce:

package main

import (
	"context"
	"fmt"
	"reflect"

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

func init() {
	validate = validator.New()

	validate.RegisterStructValidationCtx(AddressValidate, Address{})
}

var validate *validator.Validate

type (
	// User ...
	User struct {
		Name    string
		Address Address `validate:"structonly"`
	}

	// Address ...
	Address struct {
		Street string
	}
)

// AddressValidate ...
func AddressValidate(ctx context.Context, sl validator.StructLevel) {
	parent := sl.Parent().Type()
	fmt.Println(parent)

	real := reflect.TypeOf(Address{})
	expected := reflect.TypeOf(User{})

	switch parent {
	case real: // Address is nested in User. not the first call to validateStruct
		fmt.Println("why Address Parent not User")
	case expected:
		fmt.Println("expecte that Parent is User")
	}
}

func main() {
	user := new(User)

	validate.Struct(user)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions