Skip to content

Embedded structs are not validated properly #259

@manicar2093

Description

@manicar2093

System (please complete the following information):

  • OS: macOS
  • GO Version: 1.21.4
  • Pkg Version: 1.5.2

Describe the bug

Hi! I'm having troubles with embeded structs. They are not being validated correctly.

To Reproduce

package main

import (
	"fmt"
	"github.com/gookit/validate"
)

type Permission struct {
	UserData `json:",inline" validate:"required_if:Type,give"`
	Type     string `json:"type" validate:"required|in:give,remove"`
	Access   string `json:"access" validate:"required_if:Type,remove"`
}

type UserData struct {
	NameField   `json:",inline"`
	BranchField `json:",inline"`
}

type NameField struct {
	Name string `json:"name" validate:"required|max_len:5000"`
}

type BranchField struct {
	Branch string `json:"branch" validate:"required|min_len:32|max_len:32"`
}

func main() {
	// this should fail. UserData is required if type is give
	perm1 := Permission{
		UserData: UserData{},
		Type:     "give",
	}

	val1 := validate.Struct(perm1)
	val1.StopOnError = false
	if !val1.Validate() {
		// and it fails
		fmt.Println(val1.Errors.All())
	}
	fmt.Println()
	fmt.Println()
	fmt.Println()

	// This should not need UserData
	perm2 := Permission{
		Type:   "remove",
		Access: "change_types",
	}
	val2 := validate.Struct(&perm2)
	val2.StopOnError = false
	if !val2.Validate() {
		// but its asked for
		fmt.Println(val2.Errors.All())
	}
}

Expected behavior

perm2 should be fine but it fails validating UserData even when its just required if type is give.

Screenshots

If applicable, add screenshots to help explain your problem.

Additional context

Add any other context about the problem here.

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions