当前位置: 首页 > news >正文

【Golang】validator库的使用

package mainimport ("fmt""github.com/go-playground/validator"
)// MyStruct .. validate:"is-awesome"是一个结构体标签,它告诉验证器使用名为is-awesome的验证规则来验证String字段。
type MyStruct struct {String string `validate:"is-awesome"`
}// use a single instance of Validate, it caches struct info
var validate *validator.Validatefunc main() {validate = validator.New()//注册一个自定义验证函数ValidateMyVal,它将被用来验证标签为is-awesome的字段。validate.RegisterValidation("is-awesome", ValidateMyVal)s := MyStruct{String: "awesome"}err := validate.Struct(s)if err != nil {fmt.Printf("Err(s):%+v\n", err)}s.String = "not awesome"err = validate.Struct(s)if err != nil {fmt.Printf("Err(s):\n%+v\n", err)}
}// ValidateMyVal implements validator.Func
func ValidateMyVal(fl validator.FieldLevel) bool {return fl.Field().String() == "awesome"
}

custom-validation  结果

Err(s):
Key: 'MyStruct.String' Error:Field validation for 'String' failed on the 'is-awesome' tag

示例代码2

custom

package mainimport ("database/sql""database/sql/driver""fmt""reflect""github.com/go-playground/validator/v10"
)// DbBackedUser 用户结构体,由数据库支持
type DbBackedUser struct {Name sql.NullString `validate:"required"` // 可以为NULL的字符串,验证规则为必填Age  sql.NullInt64  `validate:"required"` // 可以为NULL的整数,验证规则为必填
}// 使用单一实例的验证器,它缓存结构体信息
var validate *validator.Validatefunc main() {// 创建一个新的验证器实例validate = validator.New()// 注册所有sql.Null*类型,使用自定义的ValidateValuer函数validate.RegisterCustomTypeFunc(ValidateValuer, sql.NullString{}, sql.NullInt64{}, sql.NullBool{}, sql.NullFloat64{})// 构建对象进行验证// Name字段为空字符串但Valid为true,表示非NULL;Age字段为0且Valid为false,表示NULLx := DbBackedUser{Name: sql.NullString{String: "", Valid: true}, Age: sql.NullInt64{Int64: 0, Valid: false}}// 对x进行结构体验证err := validate.Struct(x)// 如果验证失败,打印错误信息if err != nil {fmt.Printf("Err(s):\n%+v\n", err)}
}// ValidateValuer实现了validator.CustomTypeFunc接口
func ValidateValuer(field reflect.Value) interface{} {// 如果field实现了driver.Valuer接口if valuer, ok := field.Interface().(driver.Valuer); ok {// 尝试获取valuer的值val, err := valuer.Value()if err == nil {return val // 如果没有错误,返回值}// 如果有错误,可以根据需要处理}return nil // 如果没有实现Valuer接口或有错误,返回nil
}
// Struct validates a structs exposed fields, and automatically validates nested structs, unless otherwise specified.
//
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors.
func (v *Validate) Struct(s interface{}) error {return v.StructCtx(context.Background(), s)
}// StructCtx validates a structs exposed fields, and automatically validates nested structs, unless otherwise specified
// and also allows passing of context.Context for contextual validation information.
//
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors.
func (v *Validate) StructCtx(ctx context.Context, s interface{}) (err error) {val := reflect.ValueOf(s)top := valif val.Kind() == reflect.Ptr && !val.IsNil() {val = val.Elem()}if val.Kind() != reflect.Struct || val.Type().ConvertibleTo(timeType) {return &InvalidValidationError{Type: reflect.TypeOf(s)}}// good to validatevd := v.pool.Get().(*validate)vd.top = topvd.isPartial = false// vd.hasExcludes = false // only need to reset in StructPartial and StructExceptvd.validateStruct(ctx, top, val, val.Type(), vd.ns[0:0], vd.actualNs[0:0], nil)if len(vd.errs) > 0 {err = vd.errsvd.errs = nil}v.pool.Put(vd)return
}

参考validator/_examples at master · go-playground/validator · GitHub

http://www.lryc.cn/news/478114.html

相关文章:

  • 【AI日记】24.11.06 我对投资的一点浅见
  • 2024江苏省网络建设与运维省赛Linux(一)系统安装
  • 详解Python面向对象程序设计
  • JS保留两位小数
  • ClickHouse集成Mysql表引擎跨服务器读表说明
  • 【AI构思渲染】别眨眼!这些图片立马变效果图!
  • 多特征变量序列预测(10)基于麻雀优化算法的CEEMDAN-SSA-Transformer-BiLSTM预测模型
  • 算法学习(十)—— 字符串
  • 「Mac畅玩鸿蒙与硬件16」鸿蒙UI组件篇6 - List 和 Grid 组件展示数据列表
  • masm汇编字符输入小写转大写演示
  • 防火墙|WAF|漏洞|网络安全
  • 继承机制深度解析:从基础到进阶的完整指南
  • 8. 数据结构——邻接表、邻接矩阵的基本操作
  • OpenCV Python 版使用教程(二)摄像头调用
  • 基础算法——排序算法(冒泡排序,选择排序,堆排序,插入排序,希尔排序,归并排序,快速排序,计数排序,桶排序,基数排序,Java排序)
  • 几种常见的处理ARP欺骗的方法:静态ARP表和VLAN等
  • 突破1200°C高温性能极限!北京科技大学用机器学习合成24种耐火高熵合金,室温延展性极佳
  • ORA-00054: 资源正忙, 但指定以 NOWAIT 方式获取资源 或者超时失效
  • Python学习笔记-断点操作结合异常处理
  • Java实现JWT登录认证
  • 「Mac畅玩鸿蒙与硬件20」鸿蒙UI组件篇10 - Canvas 组件自定义绘图
  • 山东路远生态科技有限公司竣工投产仪式暨产品发布会圆满举行
  • java: 题目:银行账户管理系统
  • PH热榜 | 2024-11-06
  • 五、Java并发 Java Google Guava 实现
  • ssm公交车信息管理系统+vue
  • 如何删除react项目的默认图标,使在浏览器中不显示默认图标favicon.ico
  • 【React】react-app-env.d.ts 文件
  • 设计模式讲解01-建造者模式(Builder)
  • wflow-web:开源啦 ,高仿钉钉、飞书、企业微信的审批流程设计器,轻松打造属于你的工作流设计器