Skip to content

Commit 3393495

Browse files
committed
validation: fix absence detection for nullable fields
1 parent 5fa034d commit 3393495

File tree

3 files changed

+14
-3
lines changed

3 files changed

+14
-3
lines changed

validation/unique.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ var clickhouseTypes = map[reflect.Type]string{
4242
// according to the provided database scope. Uniqueness is checked using a COUNT query.
4343
type UniqueValidator struct {
4444
BaseValidator
45-
Scope func(db *gorm.DB, val any) *gorm.DB
45+
Scope func(db *gorm.DB, val any) *gorm.DB // TODO v6: change val to validation.Context
4646
}
4747

4848
// Validate checks the field under validation satisfies this validator's criteria.

validation/validator.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -449,7 +449,7 @@ func (v *validator) isAbsent(field *Field, c *walk.Context, data any) bool {
449449
Field: field,
450450
Name: c.Name,
451451
}
452-
return !field.IsRequired(requiredCtx) && !(&RequiredValidator{}).Validate(requiredCtx)
452+
return c.Found == walk.ElementNotFound && !field.IsRequired(requiredCtx)
453453
}
454454

455455
func (v *validator) processAddedErrors(ctx *Context, parentPath *walk.Path, c *walk.Context, validator Validator) {

validation/validator_test.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,16 @@ func TestValidate(t *testing.T) {
264264
},
265265
},
266266
},
267+
{
268+
desc: "absent_nullable_not_required",
269+
options: &Options{
270+
Data: map[string]any{},
271+
Language: lang.New().GetDefault(),
272+
Rules: RuleSet{
273+
{Path: "property", Rules: List{String(), Nullable()}},
274+
},
275+
},
276+
},
267277
{
268278
desc: "nil_delete_from_parent",
269279
options: &Options{
@@ -291,7 +301,8 @@ func TestValidate(t *testing.T) {
291301
{Path: "property", Rules: List{Required(), Nullable()}},
292302
},
293303
},
294-
wantData: map[string]any{"property": nil}},
304+
wantData: map[string]any{"property": nil},
305+
},
295306
{
296307
desc: "root_array",
297308
options: &Options{

0 commit comments

Comments
 (0)