github.com/gofiber/fiber/v2@v2.47.0/docs/guide/validation.md (about) 1 --- 2 id: validation 3 title: 🔎 Validation 4 sidebar_position: 5 5 --- 6 7 ## Validator package 8 9 Fiber can make _great_ use of the validator package to ensure correct validation of data to store. 10 11 * [Official validator Github page \(Installation, use, examples..\).](https://github.com/go-playground/validator) 12 13 You can find the detailed descriptions of the _validations_ used in the fields contained on the structs below: 14 15 * [Detailed docs](https://pkg.go.dev/github.com/go-playground/validator?tab=doc) 16 17 ```go title="Validation Example" 18 type Job struct{ 19 Type string `validate:"required,min=3,max=32"` 20 Salary int `validate:"required,number"` 21 } 22 23 type User struct{ 24 Name string `validate:"required,min=3,max=32"` 25 // use `*bool` here otherwise the validation will fail for `false` values 26 // Ref: https://github.com/go-playground/validator/issues/319#issuecomment-339222389 27 IsActive *bool `validate:"required"` 28 Email string `validate:"required,email,min=6,max=32"` 29 Job Job `validate:"dive"` 30 } 31 32 type ErrorResponse struct { 33 FailedField string 34 Tag string 35 Value string 36 } 37 38 var validate = validator.New() 39 func ValidateStruct(user User) []*ErrorResponse { 40 var errors []*ErrorResponse 41 err := validate.Struct(user) 42 if err != nil { 43 for _, err := range err.(validator.ValidationErrors) { 44 var element ErrorResponse 45 element.FailedField = err.StructNamespace() 46 element.Tag = err.Tag() 47 element.Value = err.Param() 48 errors = append(errors, &element) 49 } 50 } 51 return errors 52 } 53 54 func AddUser(c *fiber.Ctx) error { 55 //Connect to database 56 57 user := new(User) 58 59 if err := c.BodyParser(user); err != nil { 60 return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{ 61 "message": err.Error(), 62 }) 63 64 } 65 66 errors := ValidateStruct(*user) 67 if errors != nil { 68 return c.Status(fiber.StatusBadRequest).JSON(errors) 69 70 } 71 72 //Do something else here 73 74 //Return user 75 return c.JSON(user) 76 } 77 78 // Running a test with the following curl commands 79 // curl -X POST -H "Content-Type: application/json" --data "{\"name\":\"john\",\"isactive\":\"True\"}" http://localhost:8080/register/user 80 81 // Results in 82 // [{"FailedField":"User.Email","Tag":"required","Value":""},{"FailedField":"User.Job.Salary","Tag":"required","Value":""},{"FailedField":"User.Job.Type","Tag":"required","Value":""}]⏎ 83 ```