Validator: Is there's a way to custom error message for each field?

Created on 11 Jun 2019  Â·  6Comments  Â·  Source: go-playground/validator

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.

question

Most helpful comment

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

All 6 comments

@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:

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?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ivybridge-3c33 picture ivybridge-3c33  Â·  3Comments

dkostenko picture dkostenko  Â·  5Comments

geraldstanje picture geraldstanje  Â·  5Comments

phenrigomes picture phenrigomes  Â·  5Comments

alexyans picture alexyans  Â·  3Comments