validate
validate copied to clipboard
Return failed field if StopOnError
Is there a way to return the field that failed the validation when using StopOnError=true
for example
d := &SomeStruct{
Name: "John"
Email: "not an email"
}
v := validate.Struct(d)
if !v.validate() {
// how do i get the exact field that failed this validation?
}
Please use v.Errors, see https://github.com/gookit/validate#validate-error
I saw that but it did not serve my purpose. This is what I resolved to do.
type validationError struct {
Field string `json:"field"`
Error string `json:"error"`
}
func parseError(errs validate.Errors) validationError {
for k, _ := range errs {
return validationError{k, errs.FieldOne(k)}
}
return validationError{}
}
This way I can return the failed field & message
{
"field": "Email",
"message": "Email value is invalid email address"
}
If there is a better way to achieve this, please let me know.
Ok, thanks. I will add a helper method on Errors.
return like:
{
"field": "Email",
"message": "Email value is invalid email address"
}