What's the simplest way to customize the error message? #1084
Replies: 3 comments
-
After a bit of searching, the most straightforward method I've found is processing the errors:
Although to get what I really want I'll need to set up some cases to change the message based on the type of validation. It would be nice if I could just use a static message expressed as an annotation on the model struct |
Beta Was this translation helpful? Give feedback.
-
//This is my processing:
my pkg validator:
when some field error show errormgs |
Beta Was this translation helpful? Give feedback.
-
I use a common function: func ValidationError(structField string, err validator.ValidationErrors) string {
if len(err) == 0 {
return ""
}
for _, e := range err {
if e.StructField() == structField {
switch e.Tag() {
case "required":
return fmt.Sprintf("The %s field is required.", e.Field())
case "min":
return fmt.Sprintf("The %s field must be at least %s characters long.", e.Field(), e.Param())
case "max":
return fmt.Sprintf("The %s field must be at most %s characters long.", e.Field(), e.Param())
case "email":
return fmt.Sprintf("The %s field must be a valid email address.", e.Field())
}
}
}
return ""
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Looking to implement go-playground for validation, and looking for a clear way to customize the error message.
Right now I implemented a tag on a struct as such:
And if I call validate with a title column larger than 128 characters, I get back an error:
However, that's not sufficient information - I'd like to be able to make it read something like:
Can anyone point to an example of how to create such a custom error message?
Beta Was this translation helpful? Give feedback.
All reactions