Go语言参数校验(go-playground / validator)——基本使用

作者: adm 分类: go 发布时间: 2022-06-27

Go语言没有像Java一样的注解快速进行参数的校验,但可以通过struct tag(结构体标签)进行序列化。常用的如:

type User struct {
	ID string `json:"id"`
	Name string `json:"name"`
	Age string `json:"age"`
} 

但需要更复杂的校验,这时需要用一些专业的库来完成。go-playground / validator作为一款优秀的Go语言校验库,基于标记为结构体和单个字段实现值验证。使用简单、快捷。

添加依赖

go get github.com/go-playground/validator/v10

代码

package main
 
import (
	"fmt"
	"github.com/go-playground/validator"
)
 
var validate *validator.Validate //定义
 
type User struct {
	Name  string `validate:"required"` //非空
	Age   uint8  `validate:"gte=0,lte=130"` //  0<=Age<=130
	Email string `validate:"required,email"` //非空,email格式
	//dive关键字代表 进入到嵌套结构体进行判断
	Address []*Address `validate:"dive"` //  可以拥有多个地址
}
type Address struct {
	Province string `validate:"required"` //非空
	City     string `validate:"required"` //非空
	Phone    string `validate:"numeric,len=11"` //数字类型,长度为11
}
 
func main() {
	validate = validator.New() //初始化(赋值)
	validateStruct()           //结构体校验
	validateVariable()         //变量校验
}
func validateStruct() {
	address := Address{
		Province: "重庆",
		City:     "重庆",
		Phone:    "13366663333x",
	}
	user := User{
		Name:  "江洲",
		Age:   23,
		Email: "jz@163.com",
		Address: []*Address{&address},
	}
	err := validate.Struct(user)
	if err != nil {
		//断言为:validator.ValidationErrors,类型为:[]FieldError
		for _, e := range err.(validator.ValidationErrors) {
			fmt.Println("Namespace:", e.Namespace())
			fmt.Println("Field:", e.Field())
			fmt.Println("StructNamespace:", e.StructNamespace())
			fmt.Println("StructField:", e.StructField())
			fmt.Println("Tag:", e.Tag())
			fmt.Println("ActualTag:", e.ActualTag())
			fmt.Println("Kind:", e.Kind())
			fmt.Println("Type:", e.Type())
			fmt.Println("Value:", e.Value())
			fmt.Println("Param:", e.Param())
			fmt.Println()
		}
 
		fmt.Println("结构体输入数据类型错误!")
		return
	} else {
		fmt.Println("结构体校验通过")
	}
}
//变量校验
func validateVariable() {
	myEmail := "123@qq.com" //邮箱地址:xx@xx.com
	err := validate.Var(myEmail, "required,email")
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("变量校验通过!")
	}
}

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!