Model Validation
Iris, wisely, not features a builtin data validation. However, it does allow you to attach a validator which will automatically called on methods like Context.ReadJSON, ReadXML.... In this example we will learn how to use the go-playground/validator/v10 for request body validation.
Check the full docs and the struct tags usage here.
1
$ go get github.com/go-playground/validator/[email protected]
Copied!
Note that you need to set the corresponding binding tag on all fields you want to bind. For example, when binding from JSON, set json:"fieldname".
1
package main
2
3
import (
4
"fmt"
5
6
"github.com/kataras/iris/v12"
7
8
"github.com/go-playground/validator/v10"
9
)
10
11
// User contains user information.
12
type User struct {
13
FirstName string `json:"fname"`
14
LastName string `json:"lname"`
15
Age uint8 `json:"age" validate:"gte=0,lte=130"`
16
Email string `json:"email" validate:"required,email"`
17
FavouriteColor string `json:"favColor" validate:"hexcolor|rgb|rgba"`
18
Addresses []*Address `json:"addresses" validate:"required,dive,required"`
19
}
20
21
// Address houses a users address information.
22
type Address struct {
23
Street string `json:"street" validate:"required"`
24
City string `json:"city" validate:"required"`
25
Planet string `json:"planet" validate:"required"`
26
Phone string `json:"phone" validate:"required"`
27
}
28
29
func main() {
30
// Use a single instance of Validate, it caches struct info.
31
v := validator.New()
32
33
// Register a custom struct validation for 'User'
34
// NOTE: only have to register a non-pointer type for 'User', validator
35
// internally dereferences during it's type checks.
36
v.RegisterStructValidation(UserStructLevelValidation, User{})
37
38
app := iris.New()
39
// Register the validator to the Iris Application.
40
app.Validator = v
41
42
app.Post("/user", func(ctx iris.Context) {
43
var user User
44
45
// Returns InvalidValidationError for bad validation input,
46
// nil or ValidationErrors ( []FieldError )
47
err := ctx.ReadJSON(&user)
48
if err != nil {
49
// This check is only needed when your code could produce
50
// an invalid value for validation such as interface with nil
51
// value most including myself do not usually have code like this.
52
if _, ok := err.(*validator.InvalidValidationError); ok {
53
ctx.StatusCode(iris.StatusInternalServerError)
54
ctx.WriteString(err.Error())
55
return
56
}
57
58
ctx.StatusCode(iris.StatusBadRequest)
59
for _, err := range err.(validator.ValidationErrors) {
60
fmt.Println()
61
fmt.Println(err.Namespace())
62
fmt.Println(err.Field())
63
fmt.Println(err.StructNamespace())
64
fmt.Println(err.StructField())
65
fmt.Println(err.Tag())
66
fmt.Println(err.ActualTag())
67
fmt.Println(err.Kind())
68
fmt.Println(err.Type())
69
fmt.Println(err.Value())
70
fmt.Println(err.Param())
71
fmt.Println()
72
}
73
74
return
75
}
76
77
// [save user to database...]
78
})
79
80
app.Listen(":8080")
81
}
82
83
func UserStructLevelValidation(sl validator.StructLevel) {
84
user := sl.Current().Interface().(User)
85
86
if len(user.FirstName) == 0 && len(user.LastName) == 0 {
87
sl.ReportError(user.FirstName, "FirstName", "fname", "fnameorlname", "")
88
sl.ReportError(user.LastName, "LastName", "lname", "fnameorlname", "")
89
}
90
}
Copied!
Example request of JSON form:
1
{
2
"fname": "",
3
"lname": "",
4
"age": 45,
5
"email": "[email protected]",
6
"favColor": "#000",
7
"addresses": [{
8
"street": "Eavesdown Docks",
9
"planet": "Persphone",
10
"phone": "none",
11
"city": "Unknown"
12
}]
13
}
Copied!
Last modified 1yr ago
Export as PDF
Copy link