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) {
    32. //Connect to database
    33. user := new(User)
    34. if err := c.BodyParser(user); err != nil {
    35. c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
    36. message: err.Error(),
    37. })
    38. return
    39. }
    40. errors := ValidateStruct(*user)
    41. if errors != nil {
    42. c.JSON(errors)
    43. return
    44. }
    45. //Do something else here
    46. //Return user
    47. c.JSON(user)
    48. }
    49. // Running a test with the following curl commands
    50. // curl -X POST -H "Content-Type: application/json" --data "{\"name\":\"john\",\"isactive\":\"True\"}" http://localhost:8080/register/user
    51. // Results in
    52. // [{"FailedField":"User.Email","Tag":"required","Value":""},{"FailedField":"User.Job.Salary","Tag":"required","Value":""},{"FailedField":"User.Job.Type","Tag":"required","Value":""}]⏎