validator
validator copied to clipboard
Validate sub struct only if it exists
Package version eg. v9, v10:
v9.31.0+incompatible
Issue, Question or Enhancement:
I am trying to validate a struct, this struct has two fields that are the same struct, one of these field should be required, not the other. Is there a way to validate DateOfUpdate only if the field exists in the json feed ?
Code sample, to showcase or reproduce:
package mainpackage
import "time"
type MainStruct struct {
DateOfCreation MainStructDate `json:"dateOfCreation" validate:"omitempty"`
DateOfUpdate MainStructDate `json:"dateOfUpdate"`
}
type MainStructDate struct {
time.Time `validate:"required"`
}
The easiest way here would be to use pointers.
When using unmarshalling json into your type, if DateOfCreation is not defined in the json, then DateOfCreation will be nil. Otherwise, the omitempty tag doesn't do anything for your custom type in this example.