Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 [Bug]: Validator using Fiber v3 or v2 is not using json tags for field names. #3299

Open
3 tasks done
daibertdiego opened this issue Feb 4, 2025 · 1 comment
Open
3 tasks done

Comments

@daibertdiego
Copy link

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.

Image

How to Reproduce

Steps to reproduce the behavior:

  1. Go to '....'
  2. Click on '....'
  3. Do '....'
  4. 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.
Copy link

welcome bot commented Feb 4, 2025

Thanks for opening your first issue here! 🎉 Be sure to follow the issue template! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant