validate icon indicating copy to clipboard operation
validate copied to clipboard

Return failed field if StopOnError

Open trapcodeio opened this issue 3 years ago • 3 comments

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?
}

trapcodeio avatar Nov 14 '22 08:11 trapcodeio

Please use v.Errors, see https://github.com/gookit/validate#validate-error

inhere avatar Nov 14 '22 10:11 inhere

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.

trapcodeio avatar Nov 14 '22 11:11 trapcodeio

Ok, thanks. I will add a helper method on Errors.

return like:

{
    "field": "Email",
    "message": "Email value is invalid email address"
}

inhere avatar Nov 14 '22 13:11 inhere