validator icon indicating copy to clipboard operation
validator copied to clipboard

Method Struct(...) forms keys for embedded structures incorrectly

Open adeptxaoca opened this issue 4 years ago • 2 comments

Package version eg. v9, v10:

v10

Issue, Question or Enhancement:

The validator sees no difference between an additional field of type "struct" and embedded structures. This complicates further post-processing and forces you to pre-validate each structure and then merge the results.

Is there any way to correct this behavior? For example, by adding an additional tag.

Code sample, to showcase or reproduce:

package main

import (
	"fmt"

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

type User struct {
	Name string `validate:"required"`
}

type GroupA struct {
	Admin User
}

type GroupB struct {
	User
}

func main() {
	v := validator.New()

	errs := v.Struct(new(GroupA))
	fmt.Println("GroupA: ", errs)

	errs = v.Struct(new(GroupB))
	fmt.Println("GroupB: ", errs)
}

Output

GroupA:  Key: 'GroupA.Admin.Name' Error:Field validation for 'Name' failed on the 'required' tag
GroupB:  Key: 'GroupB.User.Name' Error:Field validation for 'Name' failed on the 'required' tag

But for "GroupB" the key "GroupB.Name" is expected.

adeptxaoca avatar May 28 '21 07:05 adeptxaoca

agree!

vm-001 avatar Apr 23 '25 10:04 vm-001

https://github.com/go-playground/validator/issues/1413#issuecomment-2805013515

deankarn avatar Apr 23 '25 13:04 deankarn