Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Partial struct validation does not validate child structs #1293

Open
josefguenther opened this issue Jul 19, 2024 · 1 comment
Open

Partial struct validation does not validate child structs #1293

josefguenther opened this issue Jul 19, 2024 · 1 comment

Comments

@josefguenther
Copy link

  • [ X ] I have looked at the documentation here first?
  • [ X ] I have looked at the examples provided that may showcase my question here?

Package version eg. v9, v10:

v10

Issue, Question or Enhancement:

When using StructPartial(), we should expect all fields specified to be validated. It does not validate struct properties, however, unless you specify the full path to individual fields inside child structs.

Code sample, to showcase or reproduce:

type Order struct {
	Id   string `validate:"required,number"`
	Item Item   `validate:"required"`
}
type Item struct {
	Id string `validate:"required,number"`
}
func TestMain(m *testing.M) {
	v := validator.New(validator.WithRequiredStructEnabled())
	order := Order{
		Id: "123",
		Item: Item{
			Id: "invalid",
		},
	}
	log.Printf("validation full: %+v", v.Struct(order))
	log.Printf("validation partial: %+v", v.StructPartial(order, "Item"))
	log.Printf("validation partial with path: %+v", v.StructPartial(order, "Item.Id"))
	log.Fatalf("done.")
	return
}

Output is as follows:

2024/07/19 15:26:07 validation full: Key: 'Order.Item.Id' Error:Field validation for 'Id' failed on the 'number' tag
2024/07/19 15:26:07 validation partial: <nil>
2024/07/19 15:26:07 validation partial with path: Key: 'Order.Item.Id' Error:Field validation for 'Id' failed on the 'number' tag
2024/07/19 15:26:07 done.
@josefguenther
Copy link
Author

josefguenther commented Jul 19, 2024

Using StructFiltered(), it does go into nested structs. However, it's a bit cumbersome to use. This works and validates all child fields in the child struct regardless of how deeply things are nested:

	log.Printf("validation filtered: %+v", v.StructFiltered(order, func(ns []byte) bool {
		if bytes.HasPrefix([]byte("Order.Item"), ns) || bytes.HasPrefix(ns, []byte("Order.Item")) {
			return false
		} else {
			return true
		}
	}))

There should be better support in StructPartial() for nested structs...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant