🔎 Validation

Validator package

Fiber can make great use of the validator package to ensure correct validation of data to store.

You can find the detailed descriptions of the validations used in the fields contained on the structs below:

  1. type Job struct{
  2. Type string `validate:"required,min=3,max=32"`
  3. Salary int `validate:"required,number"`
  4. }
  5. type User struct{
  6. Name string `validate:"required,min=3,max=32"`
  7. IsActive bool `validate:"required,eq=True|eq=False"`
  8. Email string `validate:"required,email,min=6,max=32"`
  9. Job Job `validate:"dive"`
  10. }
  11. type ErrorResponse struct {
  12. FailedField string
  13. Tag string
  14. Value string
  15. }
  16. func ValidateStruct(user User) []*ErrorResponse {
  17. var errors []*ErrorResponse
  18. validate := validator.New()
  19. err := validate.Struct(user)
  20. if err != nil {
  21. for _, err := range err.(validator.ValidationErrors) {
  22. var element ErrorResponse
  23. element.FailedField = err.StructNamespace()
  24. element.Tag = err.Tag()
  25. element.Value = err.Param()
  26. errors = append(errors, &element)
  27. }
  28. }
  29. return errors
  30. }
  31. func AddUser(c *fiber.Ctx) error {
  32. //Connect to database
  33. user := new(User)
  34. if err := c.BodyParser(user); err != nil {
  35. return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
  36. message: err.Error(),
  37. })
  38. }
  39. errors := ValidateStruct(*user)
  40. if errors != nil {
  41. return c.JSON(errors)
  42. }
  43. //Do something else here
  44. //Return user
  45. return c.JSON(user)
  46. }
  47. // Running a test with the following curl commands
  48. // curl -X POST -H "Content-Type: application/json" --data "{\"name\":\"john\",\"isactive\":\"True\"}" http://localhost:8080/register/user
  49. // Results in
  50. // [{"FailedField":"User.Email","Tag":"required","Value":""},{"FailedField":"User.Job.Salary","Tag":"required","Value":""},{"FailedField":"User.Job.Type","Tag":"required","Value":""}]⏎