Last active
March 18, 2026 07:23
-
-
Save orimdominic/50fea5dc126cd71bc7767e7570fb9e19 to your computer and use it in GitHub Desktop.
A snippet to format the errors returned from go-playground/validator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| validate = validator.New() | |
| // to get the json field namespace from the struct | |
| // omit this if you don't want to use the JSON field path/name | |
| validate.RegisterTagNameFunc(func(fld reflect.StructField) string { | |
| name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0] | |
| if name == "-" { | |
| return "" | |
| } | |
| return name | |
| }) | |
| // formatErrors returns a map of invalid fields to their error message | |
| // A sample error message is "`age` field failed validation on `min` requirement. Expected min=18 but received 10" | |
| func formatErrors(vErrs validator.ValidationErrors) []map[string]string { | |
| errs := []map[string]string{} | |
| for _, ve := range vErrs { | |
| parts := strings.SplitN(ve.Namespace(), ".", 2) | |
| fieldName := parts[1] | |
| msg := fmt.Sprintf("failed validation on `%s` requirement", ve.Tag()) | |
| if ve.Param() != "" { | |
| msg = fmt.Sprintf("%s. Expected %s=%s", msg, ve.Tag(), ve.Param()) | |
| } | |
| if ve.Param() != "" && ve.Value() != "" { | |
| msg = fmt.Sprintf("%s but received %s", msg, ve.Value()) | |
| } | |
| errs = append(errs, map[string]string{"field": fieldName, "message": msg}) | |
| } | |
| return errs | |
| } | |
| /* | |
| Sample error result | |
| [ | |
| { | |
| "field": "user.password", | |
| "message": "failed validation on `min` requirement. Expected min=6 but received paa" | |
| }, | |
| { | |
| "field": "role", | |
| "message": "failed validation on `oneof` requirement. Expected oneof=admin superadmin but received client" | |
| } | |
| ] | |
| /* |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment