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

add reflect struct field on validate error #979

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

ivybridge-3c33
Copy link

@ivybridge-3c33 ivybridge-3c33 commented Jul 28, 2022

add reflect on fields

use case:
I've added reflect.StructField for using for getting a tag for using my own custom validate message and getting the field name from the language
example use from my own project

	type test struct {
		Title string `validate:"required" json:"title" lang_key:"title"` // ex language of title = "banana"
	}
	s := test{}
	err := validate.Struct(s)
	if validate, ok := err.(*validator.InvalidValidationError); ok {
		panic(validate)
	}

	errorsFields := make(map[string][]string, 0)
	for _, validate := range err.(validator.ValidationErrors) {
		fe := validate.ReflectStructField()
		fieldName := strings.Replace(fe.Tag.Get("json"), ",omitempty", "", 0)
		if _, ok := errorsFields[fieldName]; !ok {
			errorsFields[fieldName] = make([]string, 0)
		}
		msg := ""
		switch errTagName := validate.Tag(); errTagName {
		case "regexp":
			// format :"%s invalid format blablabla"
			msg = i18n.ParseT(ct, "validator.regexp", i18n.ParseT(ct, "test."+fe.Tag.Get("lang_key"))) // banana invalid format blabla
		}
		errorsFields[fieldName] = append(errorsFields[fieldName], msg)
	}

@go-playground/validator-maintainers

@ivybridge-3c33 ivybridge-3c33 requested a review from a team as a code owner July 28, 2022 10:45
@coveralls
Copy link

coveralls commented Jul 28, 2022

Coverage Status

coverage: 74.306% (+0.02%) from 74.291%
when pulling 6074805 on fullmoon-tech:reflex-struct-field
into a947377 on go-playground:master.

@deankarn
Copy link
Contributor

@ivybridge-3c33 I like the idea of grabbing struct field, I wonder if it might be confusing though for when the validation is not a struct field.

I wonder if there would be a way for it to work with struct fields and regular ones also?

# Conflicts:
#	validator.go
#	validator_test.go
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.

4 participants