validator
validator copied to clipboard
how to validate a struct within another struct that has required field
- [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:
how do i make it so that ParentStruct will validate ChildStruct with a required field only when it is present? for example, if Child is not passed in, validation will fail on ID field for the ChildStruct which is not the intended behavior . in this case, validation should pass because Child fields was empty to begin with.
also, i am not allowed to use pointers due to resource limitations.
Code sample, to showcase or reproduce:
type ParentStruct struct {
ID string `json:"id" validate:"required"`
FirstNamae string `json:"firstName,omitempty" validate:""`
Child ChildStruct `json:"child,omitempty" validate:"omitempty"`
}
type ChildStruct struct {
ID string `json:"id" validate:"required"`
Num int `json:"num" validate:"numeric"`
}
Playground
https://play.golang.org/p/dyCnZuRnX-B
@erikvega Child field is not empty since ChildStruct.Num is an int and the default value is 0 same as ChildStruct.ID whose default is an empty string. I'd advise you to use pointers
type ParentStruct struct {
ID string `json:"id" validate:"required"`
FirstNamae string `json:"firstName,omitempty" validate:""`
Child *ChildStruct `json:"child,omitempty"`
}
@erikvega You could also use https://pkg.go.dev/github.com/go-playground/validator/v10#Validate.StructExcept and not validate the field if not needed.
If that is not a valid workaround you can always register your own validator and use that.