Created
May 9, 2020 08:58
-
-
Save hungdh0x5e/b4f73c5843331855e33157ef2f5915f4 to your computer and use it in GitHub Desktop.
Go-validator custom error message (option 1)
This file contains 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
// Usage, in controller or validate struct | |
err := ctx.ShouldBindJSON(&request) | |
if err != nil { | |
for _, fieldErr := range err.(validator.ValidationErrors) { | |
fmt.Println("error", fieldErr) | |
vgin.BuildErrorResponse(ctx, verrors.NewInvalidRequestFormatError(errors.New(validation.FieldError{fieldErr}.String()))) | |
return // exit on first error | |
} | |
} | |
// Convert tag name from StructKey to JSON tag. | |
// Exp: IDType to id_type | |
// Put before initGin | |
func RegisterTagNameJSON() { | |
validate := binding.Validator.Engine().(*validator.Validate) | |
validate.RegisterTagNameFunc(func(fld reflect.StructField) string { | |
name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0] | |
if name == "-" { | |
return "" | |
} | |
return name | |
}) | |
} | |
// Validatation | |
type FieldError struct { | |
Err validator.FieldError | |
} | |
func (q FieldError) String() string { | |
var sb strings.Builder | |
a(q.Err) | |
sb.WriteString("field '" + q.Err.Field() + "'") | |
sb.WriteString(", condition: " + q.Err.Tag()) | |
// Print condition parameters, e.g. oneof=red blue -> { red blue } | |
if q.Err.Param() != "" { | |
sb.WriteString(" { " + q.Err.Param() + " }") | |
} | |
if q.Err.Value() != nil && q.Err.Value() != "" { | |
sb.WriteString(fmt.Sprintf(", actual: %v", q.Err.Value())) | |
} | |
return sb.String() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment