Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed missing keys from returned errors in map validation #1284

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

angelo1121
Copy link

@angelo1121 angelo1121 commented Jun 21, 2024

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:

  • Tests exist or have been written that cover this particular change.

@go-playground/validator-maintainers

@angelo1121 angelo1121 requested a review from a team as a code owner June 21, 2024 15:55
@coveralls
Copy link

Coverage Status

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants