Custom error messages for StructLevel validators?
Package version eg. v8, v9:
v9
Issue, Question or Enhancement:
Let's assume I'm validating a struct and there is a string field template which should compile successfully as a valid text/template. If it doesn't compile, I want to know the underlying syntax error.
The problem is that, when I'm validating a field using validator.FieldLevel, there is only an option to return bool and no way to return additional string with an error message itself. Is there a way to workaround this?
When I'm validating a struct using validator.StructLevel, at least there is a way to report custom error messages via sl.ReportError.
Code sample, to showcase or reproduce:
// checks if a given string is valid template
func validateTemplate(fl validator.FieldLevel) bool {
_, err := template.NewTemplate(fl.Field().String())
return err == nil
}
result := validator.New()
_ = result.RegisterValidation("template", validateTemplate)
Hey @ralekseenkov sorry for the lateness of my reply,
This library mostly intends for you the user to create your own error messages, and why FieldError contains so much detail; however, there it also allows you to register i18n translations.
To do what you looking for you can register a translation for your custom validation, please see the translation docs
please let me know if that helps :)
We are already using translations and they are not going to help in this case.
If you look at the code snippet, field level validators only return true/false. There is no way to return a custom error. I.e. if I get an err from template.NewTemplate(fl.Field().String()), I can only check whether it's nil or not. There is no way to return the string of that err to an end user.
We we really want to achieve is to return Template is invalid (<underlying error message>) instead of generic Template is invalid message.
With struct-level validators it's possible to do so via sl.ReportError. Field-level validators don't seem to support that.
@ralekseenkov I see what you mean now, yes currently there is no way to do this; but it would be a great enhancement!
I will add it to the improvements for v10
ok, thanks!
if you want to take a look at how we are using the library:
- https://github.com/Aptomi/aptomi/blob/master/pkg/lang/validation.go
- https://github.com/Aptomi/aptomi/blob/master/pkg/lang/contract.go (one of the structs we are validating)
@deankarn hello, it seem that v10 does not support this way yet? Or we have to use RegisterValidationCtx?
I havnt been able to use RegisterValidationCtx with Gin to get error on custom function validators but it works with RegisterStructValidation, throwing the custom error in sl.ReportError and fetching it back up after casting it back up with validator.ValidationErrors and returning/printing it out with casted[0].Param() as demonstrated here https://github.com/go-playground/validator/blob/f1939ee4461159b2d328c77117eddf66340c0e17/_examples/struct-level/main.go