常用的开源包validator:
import gopkg.in/go-playground/validator.v8
import gopkg.in/go-playground/validator.v9
基础用法参看文档即可:
https://godoc.org/gopkg.in/go-playground/validator.v8
https://godoc.org/gopkg.in/go-playground/validator.v9
一点trick的用法:
由于golang的特性,结构体基础数据类型没有赋值会默认零值(int默认0,string默认""等),所以require不能校验出基础类型是默认零值,还是被赋为了零值。
比如:
CommType int64 `json:"comm_type"validate:"exists"`
这样无法判断是传入了0表示某种商品类型,还是根本就没传,一种解决办法是:
CommType *int64 `json:"comm_type" validate:"exists"`
改成指针类型,这样没传就是nil,传了0就不是nil,这样就区分开了,如果没传就不能通过校验。
validator是golang常用做校验的开源包,项目中常见的有v8和v9两个版本,在零值和nil的校验上有一些区别:
v8 required 和 exists 的区别:required nil和零值都不能通过检验,exists 零值能通过,nil不能通过;
v8 和 v9 的区别:v9没有exists了,统一用require,用在基础类型上零值不能通过,用在指针上nil不能通过而零值能通过
v9的做法比较好,做了统一,因为指针的零值就是nil,所以统一的来说:require零值不能通过。简洁有效!
对比表:
v8:
exists | 无 | 0 | 1 |
---|---|---|---|
int64 | √ | √ | √ |
*int64 | X | √ | √ |
require | 无 | 0 | 1 |
---|---|---|---|
int64 | X | X | √ |
*int64 | X | X | √ |
v9:
require | 无 | 0 | 1 |
---|---|---|---|
int64 | X | X | √ |
*int64 | X | √ | √ |