package scripts_stroage
import (
"fmt"
"github.com/go-playground/validator/v10"
"testing"
)
// 参考博客:
// https://juejin.cn/post/6900375680358285325
// https://www.cnblogs.com/jiujuan/p/13823864.html
type VIPUser struct {
// 1 <= len <= 20,不能为空
Name string `json:"name" validate:"required,min=1,max=20"`
// 18 <= age <= 80
Age int `json:"age" validate:"required,min=18,max=80"`
// 1<= len <= 64
Email string `json:"email" validate:"min=1,max=64"`
}
func TestTV1(t *testing.T) {
// 0:
vip0 := VIPUser{
Name: "naruto",
Age: 22,
Email: "123@qq.com",
}
va0 := validator.New()
err0 := va0.Struct(vip0)
if err0 != nil {
fmt.Println("err0: ", err0) // 输入合法没有打印
}
// 1:
vip1 := VIPUser{
Name: "whw",
Email: "www.123@qq.com",
}
va1 := validator.New()
err1 := va1.Struct(vip1)
if err1 != nil {
fmt.Println("err1: ", err1) // err1: Key: 'VIPUser.Age' Error:Field validation for 'Age' failed on the 'required' tag
}
// 2:
vip2 := VIPUser{
Name: "rrrrrrrrrrrrrrrrrrrrrrr", // name不合法
Age: 23,
Email: "", // email不合法
}
va2 := validator.New()
err2 := va2.Struct(vip2)
if err2 != nil {
fmt.Println("err2: ", err2)
/*
err2: Key: 'VIPUser.Name' Error:Field validation for 'Name' failed on the 'max' tag
Key: 'VIPUser.Email' Error:Field validation for 'Email' failed on the 'min' tag
*/
}
// 3:
vip3 := VIPUser{
Name: "whw",
Age: 555, // age不合法
Email: "123@qq.com",
}
va3 := validator.New()
err3 := va3.Struct(vip3)
if err3 != nil {
fmt.Println("err3: ", err3) // err3: Key: 'VIPUser.Age' Error:Field validation for 'Age' failed on the 'max' tag
}
}
参考博客:
https://juejin.cn/post/6900375680358285325
https://www.cnblogs.com/jiujuan/p/13823864.html