validator icon indicating copy to clipboard operation
validator copied to clipboard

Validate sub struct only if it exists

Open vhoen opened this issue 5 years ago • 1 comments

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

vhoen avatar Apr 22 '21 08:04 vhoen

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.

BrianLeishman avatar May 05 '21 19:05 BrianLeishman