Closed
Description
Bug Description
I'm using validator v10 with fiber v3 (but also tested on v2), and when I intercept validation errors, my custom messages are not using the json tag names, but the property names.
For example:
type ValidatorError struct {
Errors map[string]interface{} `json:"errors"`
}
func NewValidatorError(err error) ValidatorError {
e := ValidatorError{}
e.Errors = make(map[string]interface{})
errs := err.(validator.ValidationErrors)
for _, v := range errs {
e.Errors[v.Field()] = fmt.Sprintf("%v", v.Tag())
}
return e
}
type UserStatsCreateDTO struct {
FirstName string `json:"first_name" validate:"required"`
Age int `json:"age" validate:"required,gt=5"`
BirthDate string `json:"birth_date" validate:"required,datetime=2006/01/02"`
}
// Override default error handler
ErrorHandler: func(ctx fiber.Ctx, err error) error {
// Status code defaults to 500
code := fiber.StatusInternalServerError
// Set Content-Type: text/application-json; charset=utf-8
ctx.Set(fiber.HeaderContentType, fiber.MIMEApplicationJSON)
// Retrieve the custom status code if it's a *fiber.Error
var e *fiber.Error
if errors.As(err, &e) {
if errors.Is(err, fiber.ErrUnprocessableEntity) {
code = fiber.ErrBadRequest.Code
} else {
code = e.Code
}
}
if vldt, ok := err.(validator.ValidationErrors); ok {
validationErrors := settings.NewValidatorError(vldt)
// Return status code with error message
return ctx.Status(fiber.ErrBadRequest.Code).JSON(validationErrors)
}
// Return status code with error message
return ctx.Status(code).JSON(err.Error())
},
}),
}
func (h userStatsHandler) TestPost(c fiber.Ctx) error {
var userDTO UserStatsCreateDTO
// if err := c.BodyParser(&userDTO); err != nil {
if err := c.Bind().Body(&userDTO); err != nil {
return err
}
return c.JSON(userDTO)
}
When I try to send an invalid request using this DTO, this is my response.
How to Reproduce
Steps to reproduce the behavior:
- Go to '....'
- Click on '....'
- Do '....'
- See '....'
Expected Behavior
Receive the error msg using the json tag name like :
{
errors:[
"first_name": required,
"age": gt,
"birth_date": datetime
]
}
Fiber Version
v3
Code Snippet (optional)
package main
import "github.com/gofiber/fiber/v3"
import "log"
func main() {
app := fiber.New()
// Steps to reproduce
log.Fatal(app.Listen(":3000"))
}
Checklist:
- I agree to follow Fiber's Code of Conduct.
- I have checked for existing issues that describe my problem prior to opening this one.
- I understand that improperly formatted bug reports may be closed without explanation.