thedevsaddam/govalidator
框架介绍
另一个知名的是: asaskevich/govalidator
thedevsaddam/govalidator
借鉴 Laravel ,简单易用
表单规则
govalidator.MapData{}
MapData{}
是 map[string][]string
的自定义类型。
rules := govalidator.MapData{
"name": []string{"required", "alpha_num", "between:3,20"},
"email": []string{"required", "min:4", "max:30", "email"},
"password": []string{"required", "min:6"},
"password_confirm": []string{"required"},
}
错误消息
messages := govalidator.MapData{
"name": []string{
"required:用户名不能为空",
"alpha_num:格式错误,只允许数字和英文",
"between:用户名长度需在 3~20 之间",
},
"email": []string{
"required:邮箱不能为空",
"min:Email 长度需大于 4",
"max:Email 长度需小于 30",
"email:Email 格式不正确,请提供有效的邮箱地址",
},
"password": []string{
"required:密码为必填项",
"min:长度需大于 6",
},
"password_confirm": []string{
"required:确认密码框为必填项",
},
}
配置选项
govalidator.Options{}
type Options struct {
Data interface{} // Data represents structure for JSON body
Request *http.Request
RequiredDefault bool // RequiredDefault represents if all the fields are by default required or not
Rules MapData // Rules represents rules for form-data/x-url-encoded/query params data
Messages MapData // Messages represents custom/localize message for rules
TagIdentifier string // TagIdentifier represents struct tag identifier, e.g: json or validate etc
FormSize int64 //Form represents the multipart forom data max memory size in bytes
}
opts := govalidator.Options{
Data: &_user,
Rules: rules,
Messages: messages,
TagIdentifier: "valid", // struct 标签标识符
}
开始认证
errs := govalidator.New(opts).ValidateStruct()
验证函数命名规则
Validate{表单名称}Form
,例如注册表单就是: ValidateRegistrationForm