validator
validator copied to clipboard
Is there's a way to custom error message for each field?
Package version eg. v8, v9:
Issue, Question or Enhancement:
Code sample, to showcase or reproduce:
type User struct {
Name string `validate:"required, errMessage"`
Password string
}
I can get the errMessage in error when validate failed. PS: I don't need i18n support, just user friendly error message.
@coolerfall Currently there is no way to pull the error message from the tags, and not sure if/when I might add that.
The error message itself has all the information surrounding the error and can be used to create your error message if not using the translations logic.
i18n support is provided, optionally, through registering translations. Currently, translations are using the following packages to provide i18n/l10n:
- https://github.com/go-playground/universal-translator
- https://github.com/go-playground/locales
Thanks for sharing this.
But I need to go through all the FieldErrors
to convert to my custom message which seems not friendly/simple to use. It will be very nice if add this feature.
Just adding to @coolerfall's suggestion.
Extracting error messages into a yaml file (or any other format file) will make like easier for users to customize their error messages.
One example is from the rails world: https://github.com/rails/rails/blob/master/activemodel/lib/active_model/locale/en.yml
We could even interpolate using text/template package.
Another option is to use govalidator's solution to the problem.
type User struct {
Email string `validate:"required~email is required,email"`
Password string
}
I find this solution really clean for the user. If we want more fine grain control we can use FieldErrors
From now, is there any plans to implement this feature?
@threeaccents what if you need english, russian and french languages?
@threeaccents solution would be perfect for me, but unfortunately the govalidator library looks to be abandoned, whereas this package is still active.
In my case I want the validation errors to provide an error translation key. For example:
type User struct {
Email string `validate:"required~error-validation-email-invalid,email"`
Password string
}
Then our frontend team has a list of translation tables with mapping like:
en.json
"error-validation-email-invalid": "Please check your email is set correctly",
Our reason for doing it this way is we'd like all translations to be held in one place, rather than a mismatch between some translations happening on the backend and others on the frontend.