Skip to content

Commit

Permalink
fix error message format for maps to include the map key
Browse files Browse the repository at this point in the history
  • Loading branch information
jippi committed Feb 2, 2024
1 parent 0b97b35 commit be965b8
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
7 changes: 4 additions & 3 deletions validator_instance.go
Expand Up @@ -186,7 +186,7 @@ func (v Validate) validateMapCtx(ctx context.Context, root map[string]interface{
errs[field] = errors.New("The field: '" + field + "' is not a map to dive")
}
} else if ruleStr, ok := rule.(string); ok {
err := v.VarCtxMap(ctx, root, data[field], ruleStr)
err := v.VarCtxMap(ctx, field, root, data[field], ruleStr)
if err != nil {
errs[field] = err
}
Expand Down Expand Up @@ -668,7 +668,7 @@ func (v *Validate) VarCtx(ctx context.Context, field interface{}, tag string) (e
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors.
// validate Array, Slice and maps fields which may contain more than one error
func (v *Validate) VarCtxMap(ctx context.Context, parent interface{}, field interface{}, tag string) (err error) {
func (v *Validate) VarCtxMap(ctx context.Context, key string, parent interface{}, field interface{}, tag string) (err error) {
if len(tag) == 0 || tag == skipValidationTag {
return nil
}
Expand All @@ -679,7 +679,8 @@ func (v *Validate) VarCtxMap(ctx context.Context, parent interface{}, field inte
vd := v.pool.Get().(*validate)
vd.top = val
vd.isPartial = false
vd.traverseField(ctx, reflect.ValueOf(parent), val, vd.ns[0:0], vd.actualNs[0:0], defaultCField, ctag)

vd.traverseField(ctx, reflect.ValueOf(parent), val, vd.ns[0:0], vd.actualNs[0:0], &cField{altName: key}, ctag)

if len(vd.errs) > 0 {
err = vd.errs
Expand Down
15 changes: 15 additions & 0 deletions validator_test.go
Expand Up @@ -13280,6 +13280,21 @@ func TestValidate_ValidateMapCtx(t *testing.T) {
},
want: 1,
},

{
name: "test map with field+value reference - no brackets (fail)",
args: args{
data: map[string]interface{}{
"Field_A": "Value_A",
"Field_B": "",
},
rules: map[string]interface{}{
"Field_A": "required",
"Field_B": "required_if=Field_A Value_A",
},
},
want: 1,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down

0 comments on commit be965b8

Please sign in to comment.