Open meetsoni15 opened 1 year ago
@meetsoni15, hi, did you find a solution to this problem?
I'm also interested in it.
You can use RegisterTagNameFunc. They have an example here: https://github.com/go-playground/validator/blob/94a637ab9fbbb0bc0fe8a278f0352d0b14e2c365/validator_instance.go#L197
// RegisterTagNameFunc registers a function to get alternate names for StructFields.
//
// eg. to use the names which have been specified for JSON representations of structs, rather than normal Go field names:
//
// validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
// name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
// // skip if tag key says it should be ignored
// if name == "-" {
// return ""
// }
// return name
// })
Package version v10:
Issue, Question or Enhancement:
I have a Golang struct named BindingSearchRequest with the following definition:
I am using the validator package to validate the fields of this struct. When a validation error occurs, the validator package returns an error message that includes the field name and the validation error. For example, if the value field of the first element in the PrimarySearch slice is empty, the error message would be:
To translate this error message, I am using the universal-translator package from the go-playground/locales repository. I have registered a translation for the not_empty validation tag, as shown in the code snippet below:
This translation maps the not_empty tag to the message "{0} should not be empty!". The ut.T() function replaces the {1} placeholder with the field name.
However, I want the error message to show only the JSON tags for the fields, instead of the struct and field names. In other words, I want the error message to read:
To achieve this, I have tried using the json tag for the fields and created custom function like below:
However, this does not change the error message returned by the validator package.
Is there any way to modify the error message to show only the JSON tags for the fields? Any help would be appreciated.