validator icon indicating copy to clipboard operation
validator copied to clipboard

how to validate a struct within another struct that has required field

Open erikvegax opened this issue 3 years ago • 2 comments

  • [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

erikvegax avatar Nov 15 '21 16:11 erikvegax

@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"`
}

marymakau5 avatar Nov 29 '21 18:11 marymakau5

@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.

zemzale avatar Jan 15 '22 17:01 zemzale