go-playground / validator

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
MIT License
16.41k stars 1.3k forks source link

Return validation failure reasons to user #1093

Open kevgilmore opened 1 year ago

kevgilmore commented 1 year ago

Package version eg. v9, v10:

v10

Issue, Question or Enhancement:

Provide an easy way to relay the validation reason to the user. I.e. String must be 3 characters long

Code sample, to showcase or reproduce:

type User struct {
    Name string `json:"name" validate:"required,min=1"`
    Age  int    `json:"age" validate:"required,number"`
}

func ValidateAddUser(c *fiber.Ctx) error {
    var errors []*model.ErrorResponse
    body := new(model.User)
    _ = c.BodyParser(&body)

    err := Validator.Struct(body)
    if err != nil {
        for _, err := range err.(validator.ValidationErrors) {
            var el model.ErrorResponse
            el.FailedField = err.Field()
            el.Tag = err.Tag()
            el.Type = err.Type().String()
            errors = append(errors, &el)
        }
        return c.Status(fiber.StatusBadRequest).JSON(errors)
    }
    return c.Next()
}

app.Post("/user", util.ValidateAddUser, func(c *fiber.Ctx) error {
        body := new(model.User)
        _ = c.BodyParser(&body)
        return c.Status(fiber.StatusOK).JSON(body)
})

And when sending the following {"name": "kevin","age": 0}

The response from the above code is,

[
    {
        "FailedField": "Age",
        "Tag": "required",
        "Type": "int"
    }
]

Which doesn't convey the reason why this is a bad request (because age integer cannot be 0)