go-playground / validator

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
MIT License
17k stars 1.33k forks source link

Fixed missing keys from returned errors in map validation #1284

Open angelo1121 opened 5 months ago

angelo1121 commented 5 months ago

Fixes Or Enhances

Bug Description:

The ValidateMapCtx function calls the VarCtx(ctx context.Context, field interface{}, tag string) (err error) method, but the returned errors do not contain keys.

package main

import (
    "fmt"

    "github.com/go-playground/validator/v10"
)

func main() {
    validate := validator.New()

    data := map[string]interface{}{"email": "emailaddress"}
    rules := map[string]interface{}{"email": "required,email"}
    errs := validate.ValidateMap(data, rules) // when VarCtx is called
    fmt.Println(errs)
    //output: map[email:Key: '' Error:Field validation for '' failed on the 'email' tag]
}

Fix:

Added a new method VarWithKeyCtx(ctx context.Context, key string, field interface{}, tag string) (err error) to support validating a single variable, ensuring that the returned error contains the key of the field. This retains compatibility with the current VarCtx(...) method. Now, ValidateMapCtx will call the new VarWithKeyCtx(...) method.

package main

import (
    "fmt"

    "github.com/go-playground/validator/v10"
)

func main() {
    validate := validator.New()

    data := map[string]interface{}{"email": "emailaddress"}
    rules := map[string]interface{}{"email": "required,email"}
    errs := validate.ValidateMap(data, rules) // when the new VarWithKeyCtx is called
    fmt.Println(errs)
    //output: map[email:Key: 'email' Error:Field validation for 'email' failed on the 'email' tag]
}

Make sure that you've checked the boxes below before you submit PR:

@go-playground/validator-maintainers

coveralls commented 5 months ago

Coverage Status

coverage: 74.319% (+0.03%) from 74.291% when pulling 1152639393d3fd55dc018c134928823258636138 on angelo1121:fix-map-validation-missing-keys into a947377040f8ebaee09f20d09a745ec369396793 on go-playground:master.