From 619321c9f9cce5a8b7e2e334b916903d2148e71d Mon Sep 17 00:00:00 2001 From: Dean Karn Date: Tue, 12 Sep 2023 17:49:19 -0700 Subject: [PATCH] fix edge case (#1163) ## Fixes Or Enhances Fixes #1162 by not skipping the `required` for non nested structs accidentally introduced in last release. --- validator.go | 2 +- validator_test.go | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/validator.go b/validator.go index 2cae8f7e..342c4ec2 100644 --- a/validator.go +++ b/validator.go @@ -173,7 +173,7 @@ func (v *validate) traverseField(ctx context.Context, parent reflect.Value, curr // structs. Since it's basically nonsensical to use `required` with a non-pointer struct // are explicitly skipping the required validation for it. This WILL be removed in the // next major version. - if !v.v.requiredStructEnabled && ct != nil && ct.tag == requiredTag { + if isNestedStruct && !v.v.requiredStructEnabled && ct != nil && ct.tag == requiredTag { ct = ct.next } } diff --git a/validator_test.go b/validator_test.go index 1dfa85cc..09ff1dfe 100644 --- a/validator_test.go +++ b/validator_test.go @@ -13534,3 +13534,26 @@ func TestNestedStructValidation(t *testing.T) { }) } } + +func TestTimeRequired(t *testing.T) { + validate := New() + validate.RegisterTagNameFunc(func(fld reflect.StructField) string { + name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0] + + if name == "-" { + return "" + } + + return name + }) + + type TestTime struct { + Time time.Time `validate:"required"` + } + + var testTime TestTime + + err := validate.Struct(&testTime) + NotEqual(t, err, nil) + AssertError(t, err.(ValidationErrors), "TestTime.Time", "TestTime.Time", "Time", "Time", "required") +}