πŸ”Ž
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:
Validation Example
1
type Job struct{
2
Type string `validate:"required,min=3,max=32"`
3
Salary int `validate:"required,number"`
4
}
5
​
6
type User struct{
7
Name string `validate:"required,min=3,max=32"`
8
// use `*bool` here otherwise the validation will fail for `false` values
9
// Ref: https://github.com/go-playground/validator/issues/319#issuecomment-339222389
10
IsActive *bool `validate:"required"`
11
Email string `validate:"required,email,min=6,max=32"`
12
Job Job `validate:"dive"`
13
}
14
​
15
type ErrorResponse struct {
16
FailedField string
17
Tag string
18
Value string
19
}
20
​
21
func ValidateStruct(user User) []*ErrorResponse {
22
var errors []*ErrorResponse
23
validate := validator.New()
24
err := validate.Struct(user)
25
if err != nil {
26
for _, err := range err.(validator.ValidationErrors) {
27
var element ErrorResponse
28
element.FailedField = err.StructNamespace()
29
element.Tag = err.Tag()
30
element.Value = err.Param()
31
errors = append(errors, &element)
32
}
33
}
34
return errors
35
}
36
​
37
func AddUser(c *fiber.Ctx) error {
38
//Connect to database
39
​
40
user := new(User)
41
​
42
if err := c.BodyParser(user); err != nil {
43
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
44
"message": err.Error(),
45
})
46
47
}
48
​
49
errors := ValidateStruct(*user)
50
if errors != nil {
51
return c.JSON(errors)
52
53
}
54
​
55
//Do something else here
56
​
57
//Return user
58
return c.JSON(user)
59
}
60
​
61
// Running a test with the following curl commands
62
// curl -X POST -H "Content-Type: application/json" --data "{\"name\":\"john\",\"isactive\":\"True\"}" http://localhost:8080/register/user
63
​
64
// Results in
65
// [{"FailedField":"User.Email","Tag":"required","Value":""},{"FailedField":"User.Job.Salary","Tag":"required","Value":""},{"FailedField":"User.Job.Type","Tag":"required","Value":""}]⏎
Copied!
Last modified 1mo ago
Copy link