Versions Compared
Key
- This line was added.
- This line was removed.
- Formatting was changed.
框架校验组件内置了40+
左右常用的校验规则。GoFrame
框架校验组件内置了数十项常用的校验规则,校验组件是开发者最频繁使用的框架核心组件之一。
Note |
---|
校验规则涉及到联合校验的场景时,规则中关联的参数名称会自动按照不区分大小写且忽略特殊字符的形式进行智能匹配。 |
required
校验规则涉及到联合校验的场景时,规则中关联的参数名称会自动按照不区分大小写且忽略特殊字符的形式进行智能匹配。以下示例代码中我们均采用常用的结构体校验的方式,结构体属性中的 |
修饰规则
修饰规则本身没有任何的校验逻辑,而是修改后续功能规则的实现逻辑。
ci
- 格式:
ci
- 说明:字段值比较在默认情况下为区分大小写严格匹配比较,通过
ci(Case Insensitive)
修饰规则,可以设置后续需要比较值的规则字段为不区分大小写。如:same
,different
,in
,not-in
等。 示例:
- 格式:
required
- 说明:必需参数,除了支持常见的字符串,也支持
Slice/Map
类型。 示例:姓名字段 Code Block language go func
ExampleValidatorExample_Rule_
RequiredCaseInsensitive() { type BizReq struct {
IdAccount
uintstring `v:"required"` Password string `v:"required|ci|same:Password2"`
NamePassword2 string `v:"required"` } var ( ctx = context.Background() req = BizReq{
IdAccount:
1"gf",
}
)
if err := g.Validator().CheckStruct(ctx, req)Password: "Goframe.org", // Diff from Password2, but because of "ci", rule check passed Password2: "goframe.org", } ) if err := g.Validator().Data(req).Run(ctx); err != nil { fmt.Println(err) } //
Output:
// The Name field is requiredoutput: }
Name
为必需参数必需不能为空。required-if
bail
Note |
---|
需要特别注意:如果参数校验存在多条校验规则,并且规则中存在 |
- 格式:
bail
- 说明:只要后续的多个校验中有一个规则校验失败则停止校验并立即返回校验结果。
- 注意:在框架的
HTTP Server
组件中,如果采用规范路由注册方式,在其自动校验特性中将会自动开启bail
修饰规则,开发者无需在Req
对象中显式设置bail
。 示例:
- 格式:
required-if:field,value,...
- 说明:必需参数(当任意所给定字段值与所给值相等时,即:当
field
字段的值为value
时,当前验证字段为必须参数)。 示例:当
Gender
字段为1
时WifeName
字段必须不为空, 当Gender
字段为2
时HusbandName
字段必须不为空。Code Block language go func ExampleValidatorExample_Rule_RequiredIfBail() { type BizReq struct { IdAccount uint string `v:"required" dc:"Your Id"bail|required|length:6,16|same:QQ"` NameQQ string Password string `v:"required|same:Password2" dc` Password2 string `v:"Your namerequired"` } Gendervar ( ctx = context.Background() req uint `v:"in:0,1,2" dc:"0:Secret;1:Male;2:Female"` WifeName string `v:"required-if:gender,1"` HusbandName string `v:"required-if:gender,2"` } var ( ctx = context.Background() req = BizReq{ Id:= BizReq{ Account: "gf", QQ: 1"123456", NamePassword: "testgoframe.org", GenderPassword2: 1"goframe.org", } ) if err := g.Validator().CheckStruct(ctx, reqData(req).Run(ctx); err != nil { fmt.Println(err) } // Outputoutput: // The WifeName field is required }
required-unless
Account value `gf` length must be between 6 and 16 }
foreach
- 格式:
foreach
- 说明:用于数组参数,将待检验的参数作为数组遍历,并将后一个校验规则应用于数组中的每一项。
- 版本:框架版本
>=v2.2.0
示例:
- 格式:
required-unless:field,value,...
- 说明:必需参数(当所给定字段值与所给值都不相等时,即:当
field
字段的值不为value
时,当前验证字段为必须参数)。 示例:当
Gender
不等于0
且Gender
不等于2
时,WifeName
必须不为空;当Id
不等于0
且Gender
不等于2
时,HusbandName
必须不为空。Code Block language go func ExampleValidatorExample_Rule_RequiredUnlessForeach() { type BizReq struct { Id uint Value1 []int `v:"required" dc:"Your Idforeach|in:1,2,3"` Name stringValue2 []int `v:"required" dc:"Your name"` Gender uint `v:"in:0,1,2" dc:"0:Secret;1:Male;2:Female"` WifeName string `v:"required-unless:gender,0,gender,2"` HusbandName string `v:"required-unless:id,0,gender,2foreach|in:1,2,3"` } var ( ctx = context.Background() req = BizReq{ IdValue1: []int{1, 12, 3}, NameValue2: "test", Gender: 1[]int{3, 4, 5}, } ) if err := g.Validator().CheckStructBail().Data(req).Run(ctx, req); err != nil { fmt.Println(err.String()) } // Output: // The WifeNameValue2 value field`4` is required;not Thein HusbandNameacceptable field is requiredrange: 1,2,3 }
功能规则
功能规则实现特定的校验逻辑,框架内置了非常丰富强大的内置校验规则。
required
-with- 格式:
required-with:field1,field2,...
- 说明:必需参数(当所给定任意字段值不为空时)。 示例:当
- 说明:必需参数,除了支持常见的字符串,也支持
Slice/Map
类型。 示例:姓名字段
Name
为必需参数必需不能为空。Code Block language go func
ExampleValidatorExample_Rule_
RequiredWithRequired()
{ type BizReq struct {
Id ID
uint `v:"required"
dc:"Your Id"`
Name string ` Name string `v:"required
" dc:"
Your name"`
Gender uint `v:"in:0,1,2" dc:"0:Secret;1:Male;2:Female"`
WifeName string
HusbandName string `v:"required-with:WifeName"`
} var ( ctx = context.Background() req = BizReq{
IdID:
1,
Name: "test",
Gender: 1,
WifeName: "Ann",
}
)
if err := g.Validator().CheckStruct(ctx, req} ) if err := g.Validator().Data(req).Run(ctx); err != nil { fmt.
PrintlnPrint(err) } // Output: // The
HusbandNameName field is required }
WifeName
不为空时,HusbandName
必须不为空。required-
with-allif
- 格式:
required-with-allif:field1field,field2value,...
- 说明:必须参数(当所给定所有字段值都不为空时)。
- 说明:必需参数(当任意所给定字段值与所给值相等时,即:当
field
字段的值为value
时,当前验证字段为必须参数)。多个字段以,
号分隔。 示例:当
Gender
字段为1
时WifeName
字段必须不为空, 当Gender
字段为2
时HusbandName
字段必须不为空。示例:当Id,Name,Gender,WifeName
全部不为空时,HusbandName
必须不为空。Code Block language go func ExampleValidatorExample_Rule_RequiredWithAllRequiredIf() { type BizReq struct { IdID uint `v:"required" dc:"Your IdID"` Name string `v:"required" dc:"Your name"` Gender uint `v:"in:0,1,2" dc:"0:Secret;1:Male;2:Female"` WifeName string HusbandName string `v:"required-with-allif:Id,Name,Gender,WifeNamegender,1"` HusbandName string `v:"required-if:gender,2"` } var ( ctx = context.Background() req = BizReq{ IdID: 1, Name: "test", Gender: 1, WifeName: "Ann", } ) if err := g.Validator().Data(req).CheckStructRun(ctx, req); err != nil { fmt.Println(err) } // Output: // The HusbandNameWifeName field is required }
required-
withoutunless
- 格式:
required-withoutunless:field1field,field2value,...
- 说明:必需参数(当所给定任意字段值为空时)。当所给定字段值与所给值都不相等时,即:当
field
字段的值不为value
时,当前验证字段为必须参数)。多个字段以,
号分隔。 示例:当
Gender
不等于0
且Gender
不等于2
时,WifeName
必须不为空;当Id
不等于0
且Gender
不等于2
时, 示例:当Id
或WifeName
为空时,HusbandName
必须不为空。Code Block language go func ExampleValidatorExample_Rule_RequiredWithoutRequiredUnless() { type BizReq struct { IdID uint `v:"required" dc:"Your IdID"` Name string `v:"required" dc:"Your name"` Gender uint `v:"in:0,1,2" dc:"0:Secret;1:Male;2:Female"` WifeName string string `v:"required-unless:gender,0,gender,2"` HusbandName string `v:"required-without:Id,WifeNameunless:id,0,gender,2"` } var ( ctx = context.Background() req = BizReq{ IdID: 1, Name: "test", Gender: 1, } ) if err := g.Validator().Data(req).CheckStructRun(ctx, req); err != nil { fmt.Println(err) } // Output: // The WifeName field is required; The HusbandName field is required }
required-
without-allwith
- 格式:
required-without-allwith:field1,field2,...
- 说明:必须参数说明:必需参数(当所给定所有字段值都为空时当所给定任意字段值其中之一不为空时)。
示例:当
Id
和WifeName
都为空时,不为空时,HusbandName
必须不为空。Code Block language go func ExampleValidatorExample_Rule_RequiredWithoutAllRequiredWith() { type BizReq struct { IdID uint `v:"required" dc:"Your IdID"` Name string `v:"required" dc:"Your name"` Gender uint `v:"in:0,1,2" dc:"0:Secret;1:Male;2:Female"` WifeName string HusbandName string `v:"required-without-allwith:Id,WifeName"` } var ( ctx = context.Background() req = BizReq{ NameID: "test"1, Gender: Name: "test", Gender: 1, WifeName: "Ann", } ) if err := g.Validator().CheckStructData(req).Run(ctx, req); err != nil { fmt.Println(err) } // Output: // The HusbandName field is required }
date
required-with-all
- 格式:
date
- 说明:参数为常用日期类型,日期之间支持的连接符号
-
或/
或.
,也支持不带连接符号的8
位长度日期,格式如:2006-01-02
,2006/01/02
,2006.01.02
,20060102
-
required-with-all:field1,field2,...
- 说明:必须参数(当所给定所有字段值全部都不为空时)。
示例:当
Id,Name,Gender,WifeName
全部不为空时,HusbandName
必须不为空。示例:Code Block language go func ExampleValidatorExample_Rule_DateRequiredWithAll() { type BizReq struct { Date1 string `v:"dateID uint `v:"required" dc:"Your ID"` Date2Name string string `v:"required" dc:"dateYour name"` Date3 stringGender uint `v:"datein:0,1,2" dc:"0:Secret;1:Male;2:Female"` Date4WifeName string `v:"date"` Date5HusbandName string `v:"daterequired-with-all:Id,Name,Gender,WifeName"` } var ( ctx = context.Background() req = BizReq{ Date1ID: "2021-10-31" 1, Date2Name: "2021.10.31 "test", Date3Gender: "2021-Oct-31" 1, Date4WifeName: "2021 Octa 31Ann", Date5: "2021/Oct/31", } ) if err := g.Validator().CheckStructData(req).Run(ctx, req); err != nil { fmt.PrintPrintln(err) } // Output: // The Date3HusbandName valuefield is not a valid date; The Date4 value is not a valid date; The Date5 value is not a valid date }
datetime
required }
required-without
- 格式:
required-without:field1,field2,...
- 说明:必需参数(当所给定任意字段值其中之一为空时)。
示例:当
Id
或WifeName
为空时,HusbandName
必须不为空。Code Block language go func Example_Rule_RequiredWithout() { type BizReq struct { ID uint `v:"required" dc:"Your ID"` Name
- 格式:
datetime
- 说明:参数为常用日期时间类型,其中日期之间支持的连接符号只支持
-
,格式如:2006-01-02 12:00:00
示例:
Code Block language go func ExampleValidator_Datetime() { type BizReq struct { Date1 string `v:"datetimerequired"` Date2 string `v dc:"datetimeYour name"` Date3 stringGender uint `v:"datetime"` Date4 string `v:"datetime"` } in:0,1,2" dc:"0:Secret;1:Male;2:Female"` WifeName string HusbandName string `v:"required-without:Id,WifeName"` } var ( ctx = context.Background() req = BizReq{ Date1ID: "2021-11-01 23:00:00" 1, Date2Name: "2021-11-01 23:00", // error Date3: "2021/11/01 23:00:00", // error"test", Date4Gender: "2021/Dec/01 23:00:00", // error1, } ) if err := g.Validator().CheckStructData(req).Run(ctx, req); err != nil { fmt.PrintPrintln(err) } // Output: // The Date2HusbandName valuefield is not a valid datetime; The Date3 value is not a valid datetime; The Date4 value is not a valid datetimerequired }
required-without-
formatall
- 格式:
daterequired-without-format:format
- 说明:判断日期是否为指定的日期格式,
format
参数格式为gtime
日期格式(可以包含日期及时间),格式说明参考章节:gtime模块 all:field1,field2,...
- 说明:必须参数(当所给定所有字段值全部都为空时)。
示例:当
Id
和WifeName
都为空时,HusbandName
必须不为空。示例:date-format:Y-m-d H:i:s
Code Block language go func ExampleValidatorExample_Rule_DateFormatRequiredWithoutAll() { type BizReq struct { Date1 stringID uint `v:"date-format:Y-m-drequired" dc:"Your ID"` Date2Name string `v:"date-format:Y-m-d"required" dc:"Your name"` Date3 stringGender uint `v:"date-format:Y-m-d H:i:s"` Date4in:0,1,2" dc:"0:Secret;1:Male;2:Female"` WifeName string HusbandName string `v:"daterequired-format:Y-m-d H:i:swithout-all:Id,WifeName"` } var ( ctx = context.Background() req = BizReq{ Date1Name: "2021-11-01", "test", Date2Gender: "2021-11-01 23:00", // error Date3: "2021-11-01 23:00:00", Date4: "2021-11-01 23:00", // error 1, } ) if err := g.Validator().Data(req).CheckStructRun(ctx, req); err != nil { fmt.PrintPrintln(err) } // Output: // The Date2HusbandName valuefield does not match the format Y-m-d; The Date4 value does not match the format Y-m-d H:i:s }
email
is required }
date
- 格式:
date
- 说明:参数为常用日期类型,日期之间支持的连接符号
-
或/
或.
,也支持不带连接符号的8
位长度日期,格式如:2006-01-02
,2006/01/02
,2006.01.02
,20060102
示例:
- 格式:
email
说明:
EMAIL
邮箱地址Code Block language go func ExampleValidatorExample_Rule_EmailDate() { type BizReq struct { MailAddr1Date1 string `v:"date"` Date2 string `v:"emaildate"` MailAddr2Date3 string `v:"emaildate"` MailAddr3Date4 string `v:"emaildate"` MailAddr4Date5 string `v:"emaildate"` } var ( ctx = context.Background() req = BizReq{ MailAddr1Date1: "gf@goframe.org2021-10-31", MailAddr2Date2: "gf@goframe2021.10.31", // error MailAddr3Date3: "gf@goframe.org.cn2021-Oct-31", MailAddr4Date4: "gf#goframe.org2021 Octa 31", Date5: "2021/Oct/ error31", } ) if err := g.Validator().CheckStructData(req).Run(ctx, req); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: // The MailAddr2Date3 value must be`2021-Oct-31` is not a valid email address; date // The MailAddr4Date4 value must`2021 beOcta a31` validis email address }
phone
not a valid date // The Date5 value `2021/Oct/31` is not a valid date }
datetime
- 格式:
datetime
- 说明:参数为常用日期时间类型,其中日期之间支持的连接符号只支持
-
,格式如:2006-01-02 12:00:00
示例:
Code Block language go func Example_Rule_Datetime() { type BizReq struct { Date1
- 格式:
phone
说明:手机号
Code Block language go func ExampleValidator_Phone() { type BizReq struct { PhoneNumber1 string `v:"phonedatetime"` PhoneNumber2Date2 string `v:"phonedatetime"` PhoneNumber3Date3 string `v:"phonedatetime"` PhoneNumber4Date4 string `v:"phonedatetime"` } var ( ctx = context.Background() req = BizReq{ PhoneNumber1Date1: "135789123452021-11-01 23:00:00", PhoneNumber2Date2: "11578912345", 2021-11-01 23:00", // error 11x not exist PhoneNumber3Date3: "171789123452021/11/01 23:00:00", // error 171 not exit PhoneNumber4Date4: "13578912342021/Dec/01 23:00:00", // error len must be 11 } ) if err := g.Validator().CheckStructData(req).Run(ctx, req); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: // The PhoneNumber2Date2 value must be `2021-11-01 23:00` is not a valid phone number; datetime // The PhoneNumber3Date3 value must be `2021/11/01 23:00:00` is not a valid phone number;datetime // The PhoneNumber4Date4 value must be `2021/Dec/01 23:00:00` is not a valid phone numberdatetime }
date-
looseformat
- 格式:
phone
:date-format:format
- 说明:判断日期是否为指定的日期/时间格式,
format
参数格式为gtime
日期格式(可以包含日期及时间),格式说明参考章节:gtime模块 示例:
date-format:Y-m-d H:i:s
说明:宽松的手机号验证,只要满足13、14、15、16、17、18、19
开头的11位数字都可以通过验证。Code Block language go func ExampleValidatorExample_Rule_PhoneLooseDateFormat() { type BizReq struct { PhoneNumber1Date1 string `v:"phone-loosedate-format:Y-m-d"` PhoneNumber2Date2 string `v:"phone-loosedate-format:Y-m-d"` PhoneNumber3Date3 string `v:"phone-loosedate-format:Y-m-d H:i:s"` PhoneNumber4Date4 string `v:"phone-loosedate-format:Y-m-d H:i:s"` } var ( ctx = context.Background() req = BizReq{ PhoneNumber1Date1: "135789123452021-11-01", PhoneNumber2Date2: "115789123452021-11-01 23:00", // error 11x not exist PhoneNumber3Date3: "171789123452021-11-01 23:00:00", PhoneNumber4Date4: "13578912342021-11-01 23:00", // error len must be 11 } ) if err := g.Validator().CheckStructData(req).Run(ctx, req); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: // The PhoneNumber2Date2 value must be a valid phone number; The PhoneNumber4 value must be a valid phone number }
telephone
`2021-11-01 23:00` does not match the format: Y-m-d // The Date4 value `2021-11-01 23:00` does not match the format: Y-m-d H:i:s }
before
- 格式:
before:field
说明:判断给定的日期/时间是否在指定字段的日期/时间之前。
- 版本:框架版本
>=v2.2.0
- 格式:
telephone
- 说明:国内座机电话号码,”XXXX-XXXXXXX”、”XXXX-XXXXXXXX”、”XXX-XXXXXXX”、”XXX-XXXXXXXX”、”XXXXXXX”、”XXXXXXXX”
Code Block language go func ExampleValidatorExample_Rule_TelephoneBefore() { type BizReq struct { Telephone1Time1 string `v:"telephonebefore:Time3"` Telephone2Time2 string `v:"telephonebefore:Time3"` Telephone3Time3 string `v:"telephone"` } var ( Telephone4ctx string `v:"telephone"` } var ( ctx = = context.Background() req = BizReq{ Telephone1Time1: "0102022-09-7754214502", Telephone2Time2: "05712022-09-7754214503", Telephone3Time3: "202022-09-7754214503", // error Telephone4: "775421451", // error len must be 7 or 8 } ) if err := g.Validator().CheckStructData(req).Run(ctx, req); err != nil { fmt.PrintPrintln(err.String()) } // Output: // The Telephone3Time2 value `2022-09-03` must be abefore validfield telephone number; The Telephone4 value must be a valid telephone number }
passport
Time3 value `2022-09-03` }
before-equal
- 格式:
before-equal:field
说明:判断给定的日期/时间是否在指定字段的日期/时间之前,或者与指定字段的日期/时间相等。
版本:框架版本
>=v2.2.0
- 格式:
passport
说明:通用帐号规则(字母开头,只能包含字母、数字和下划线,长度在6~18之间)。
Code Block language go func ExampleValidatorExample_Rule_PassportBeforeEqual() { type BizReq struct { Passport1Time1 string `v:"passportbefore-equal:Time3"` Passport2Time2 string `v:"passport"` Passport3 string `v:"passportbefore-equal:Time3"` Passport4Time3 string `v:"passport"` } var ( ctx = context.Background() req = BizReq{ Passport1Time1: "goframe2022-09-02", Passport2Time2: "13566662022-09-01", // error starting with letter Passport3Time3: "goframe#", // error containing only numbers or underscores Passport4: "gf", // error length between 6 and 18 2022-09-01", } ) if err := g.Validator().CheckStructData(req).Run(ctx, req); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: // The Passport2Time1 value is not a valid passport format; The Passport3 value is not a valid passport format; The Passport4 value is not a valid passport format }
password
`2022-09-02` must be before or equal to field Time3 }
after
- 格式:
after:field
说明:判断给定的日期/时间是否在指定字段的日期/时间之后。
- 格式:
password
- 版本:框架版本
>=v2.2.0
说明:通用密码规则(任意可见字符,长度在6~18之间)。
Code Block language go func ExampleValidatorExample_Rule_PasswordAfter() { type BizReq struct { Password1Time1 string Time2 string `v:"passwordafter:Time1"` Password2Time3 string `v:"passwordafter:Time1"` } var ( ctx = context.Background() req = BizReq{ Password1Time1: "goframe2022-09-01", Password2Time2: "gofra2022-09-01", // error length between 6 and 18Time3: "2022-09-02", } ) if err := g.Validator().CheckStructData(ctx, req).Run(ctx); err != nil { fmt.PrintPrintln(err.String()) } // Output: // The Password2Time2 value is not a valid passport format }
password2
`2022-09-01` must be after field Time1 value `2022-09-01` }
after-equal
- 格式:
after-equal:field
说明:判断给定的日期/时间是否在指定字段的日期/时间之后,或者与指定字段的日期/时间相等。
版本:框架版本
>=v2.2.0
- 格式:
password2
说明:中等强度密码(在弱密码的基础上,必须包含大小写字母和数字)。
Code Block language go func ExampleValidatorExample_Rule_Password2AfterEqual() { type BizReq struct { Password1Time1 string `v:"password2"` Password2Time2 string `v:"password2after-equal:Time1"` Password3Time3 string `v:"password2"` Password4 string `v:"password2after-equal:Time1"` } var ( ctx = context.Background() req = BizReq{ Password1Time1: "Goframe1232022-09-02", Password2Time2: "gofra", // error length between 6 and 182022-09-01", Password3Time3: "Goframe", // error must contain lower and upper letters and numbers. Password4: "goframe123", // error must contain lower and upper letters and numbers. 2022-09-02", } ) if err := g.Validator().Data(req).CheckStructRun(ctx, req); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: // The Password2Time2 value is not a valid passport format; The Password3 value is not a valid passport format; The Password4 value is not a valid passport format }
password3
`2022-09-01` must be after or equal to field Time1 value `2022-09-02` }
array
- 格式:
array
说明:判断给定的参数是否数组格式。如果给定的参数为
JSON
数组字符串,也将检验通过。- 格式:
password3
- 版本:框架版本
>=v2.2.0
说明:强等强度密码(在弱密码的基础上,必须包含大小写字母、数字和特殊字符)。
Code Block language go func ExampleValidatorExample_Rule_Password3Array() { type BizReq struct { Value1 string `v:"array"` Password1Value2 string `v:"password3array"` Password2Value3 string `v:"password3array"` Password3Value4 []string `v:"password3array"` } var ( ctx = context.Background() req = BizReq{ Password1Value1: "Goframe123#", 1,2,3", Password2Value2: "gofra[]", // error length between 6 and 18 Password3Value3: "Goframe123[1,2,3]", // error must contain lower and upper letters, numbers and special chars.Value4: []string{}, } ) if err := g.Validator().Data(req).CheckStructRun(ctx, req); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: // The Password2Value1 value `1,2,3` is not aof valid passport format; The Password3 value is not a valid passport format }
postcode
array type }
enums
- 格式:
enums
说明:校验提交的参数是否在字段类型的枚举值中。该规则需要结合
gf gen enums
命令一起使用,详情请参考:枚举维护-gen enums- 格式:
postcode
说明:中国邮政编码
Code Block language go func ExampleValidatorExampleRule_PostcodeEnums() { type Status string const ( StatusRunning Status = "Running" StatusOffline Status = "Offline" ) type BizReq struct { Postcode1 stringId int `v:"postcoderequired"` Postcode2Name string `v:"postcoderequired"` Postcode3Status stringStatus `v:"postcodeenums"` } var ( ctx = context.Background() req = BizReq{ Postcode1Id: "100000" 1, Postcode2Name: "10000john", // error length must be 6 Postcode3: "1000000", // error length must be 6 Status: Status("Pending"), } ) if err := g.Validator().Data(req).CheckStructRun(ctx, req); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // May Output: // The Postcode2Status value is`Pending` notshould abe validin passportenums format; The Postcode3 value is not a valid passport format }
resident-id
of: ["Running","Offline"] }
email
- 格式:
email
说明:
EMAIL
邮箱地址格式。- 格式: resident-id
说明:公民身份证号码
Code Block language go func ExampleValidatorExample_Rule_ResidentIdEmail() { type BizReq struct { ResidentId1MailAddr1 string `v:"email"` MailAddr2 string `v:"email"` MailAddr3 string `v:"email"` MailAddr4 string `v:"resident-idemail"` } var ( ctx = context.Background() req = BizReq{ ResidentId1MailAddr1: "gf@goframe.org", MailAddr2: "gf@goframe", // error MailAddr3: "gf@goframe.org.cn", MailAddr4: "320107199506285482gf#goframe.org", // error } ) if err := g.Validator().CheckStructData(ctx, req);.Run(ctx); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: // The ResidentId1MailAddr2 value `gf@goframe` is not a valid resident id numberemail address // The MailAddr4 value `gf#goframe.org` is not a valid email address }
bank-card
phone
- 格式:
phone
说明:大中国区手机号格式。
- 格式: bank-card
说明:银行卡号校验
Code Block language go func ExampleValidatorExample_Rule_BankCardPhone() { type BizReq struct { PhoneNumber1 string `v:"phone"` PhoneNumber2 string `v:"phone"` PhoneNumber3 string `v:"phone"` BankCard1PhoneNumber4 string `v:"bank-cardphone"` } var ( ctx = context.Background() req = BizReq{ BankCard1PhoneNumber1: "6225760079930218", 13578912345", PhoneNumber2: "11578912345", // error 11x not exist PhoneNumber3: "17178912345", // error 171 not exit PhoneNumber4: "1357891234", // error len must be 11 } ) if err := g.Validator().CheckStructData(req).Run(ctx, req); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: // The BankCard1PhoneNumber2 value `11578912345` mustis benot a valid bank card number }
qq
phone number // The PhoneNumber3 value `17178912345` is not a valid phone number // The PhoneNumber4 value `1357891234` is not a valid phone number }
phone-loose
- 格式:
phone
说明:宽松的手机号验证,只要满足
13、14、15、16、17、18、19
开头的11位数字都可以通过验证。可用于非严格的业务场景。- 格式:
qq
说明:腾讯QQ号码
Code Block language go func ExampleValidatorExample_Rule_QQPhoneLoose() { type BizReq struct { QQ1PhoneNumber1 string `v:"phone-loose"` PhoneNumber2 string `v:"qqphone-loose"` QQ2PhoneNumber3 string `v:"qqphone-loose"` QQ3PhoneNumber4 string `v:"qqphone-loose"` } var ( ctx = context.Background() req = BizReq{ QQ1PhoneNumber1: "38996181713578912345", QQ2PhoneNumber2: "999911578912345", // error 11x >=not 10000exist QQ3PhoneNumber3: "514258412a17178912345", // PhoneNumber4: "1357891234", // error len must allbe number11 } ) if err := g.Validator().Data(req).CheckStructRun(ctx, req); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: // The QQ2PhoneNumber2 value must`11578912345` be a valid QQ number; The QQ3is invalid // The PhoneNumber4 value must`1357891234` be a valid QQ numberis invalid }
ip
telephone
- 格式:
ip
telephone
说明:大中国区座机电话号码,”XXXX-XXXXXXX”、”XXXX-XXXXXXXX”、”XXX-XXXXXXX”、”XXX-XXXXXXXX”、”XXXXXXX”、”XXXXXXXX”。说明:
IPv4/IPv6
地址Code Block language go func ExampleValidatorExample_Rule_IPTelephone() { type BizReq struct { IP1Telephone1 string `v:"iptelephone"` IP2Telephone2 string `v:"iptelephone"` IP3Telephone3 string `v:"iptelephone"` IP4Telephone4 string `v:"iptelephone"` } var ( ctx = context.Background() req = BizReq{ IP1Telephone1: "127.0.0.1010-77542145", IP2Telephone2: "fe80::812b:1158:1f43:f0d10571-77542145", IP3Telephone3: "520.255.255.255", 20-77542145", // error IP4Telephone4: "ze80::812b:1158:1f43:f0d1",775421451", // error len must be 7 or 8 } ) if err := g.Validator().Data(req).CheckStructRun(ctx, req); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: // The IP3Telephone3 value must be`20-77542145` is not a valid IP address;telephone number // The IP4Telephone4 value must`775421451` is benot a valid IPtelephone addressnumber }
ipv4
passport
- 格式:
ipv4
passport
说明:通用帐号规则(字母开头,只能包含字母、数字和下划线,长度在6~18之间)。说明:
IPv4
地址Code Block language go func ExampleValidatorExample_Rule_IPV4Passport() { type BizReq struct { IP1Passport1 string `v:"passport"` Passport2 string `v:"passport"` Passport3 string `v:"ipv4passport"` IP2Passport4 string `v:"ipv4passport"` } var ( ctx = context.Background() req = BizReq{ IP1Passport1: "127.0.0.1goframe", IP2Passport2: "520.255.255.255",1356666", // error starting with letter } ) if err := g.Validator().CheckStruct(ctx, req); err Passport3: "goframe#", // error containing only numbers or underscores Passport4: "gf", // error length between 6 and 18 } ) if err := g.Validator().Data(req).Run(ctx); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: // The IP2Passport2 value `1356666` mustis benot a valid IPv4passport address }
ipv6
format // The Passport3 value `goframe#` is not a valid passport format // The Passport4 value `gf` is not a valid passport format }
password
- 格式:
password
说明:通用密码规则(任意可见字符,长度在6~18之间)。
- 格式:
ipv6
说明:
IPv6
地址Code Block language go func ExampleValidatorExample_Rule_IPV6Password() { type BizReq struct { IP1Password1 string `v:"ipv6password"` IP2Password2 string `v:"ipv6password"` } var ( ctx = context.Background() req = BizReq{ IP1Password1: "fe80::812b:1158:1f43:f0d1goframe", IP2Password2: "ze80::812b:1158:1f43:f0d1",gofra", // error length between 6 and 18 } ) if err := g.Validator().Data(req).CheckStructRun(ctx, req); err != nil { fmt.Print(err) } // Output: // The IP2Password2 value must`gofra` beis not a valid IPv6password addressformat }
mac
password2
- 格式:
mac
password2
说明:中等强度密码(在通用密码规则的基础上,要求密码必须包含大小写字母和数字)。说明:
MAC
地址Code Block language go func ExampleValidatorExample_Rule_MacPassword2() { type BizReq struct { Mac1Password1 string `v:"password2"` Password2 string `v:"password2"` Password3 string `v:"macpassword2"` Mac2Password4 string `v:"macpassword2"` } var ( ctx = context.Background() req = BizReq{ Mac1Password1: "4C-CC-6A-D6-B1-1AGoframe123", Mac2Password2: "Z0-CC-6A-D6-B1-1A", } ) if err := g.Validator().CheckStruct(ctx, req); err != nil { fmt.Print(err) } // Output: // The Mac2 value must be a valid MAC address }
url
- 格式:
url
- 说明:URL
示例:支持以
http,https,ftp,file
开头的地址。Code Block language go func ExampleValidator_Url() { type BizReq struct { Url1 string `v:"url"` Url2 string `v:"url"` Url3 string `v:"url"` } var ( ctx = context.Background() req = BizReq{ Url1: "http://goframe.org", Url2: "ftp://goframe.org", Url3: "ws://goframe.org", } ) if err := g.Validator().CheckStruct(ctx, req); err != nil { fmt.Print(err) } // Output:gofra", // error length between 6 and 18 Password3: "Goframe", // error must contain lower and upper letters and numbers. Password4: "goframe123", // error must contain lower and upper letters and numbers. } ) if err := g.Validator().Data(req).Run(ctx); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: // The Password2 value `gofra` is not a valid password format // The Password3 value `Goframe` is not a valid password format // The Url3Password4 value `goframe123` mustis benot a valid URLpassword addressformat }
domain
password3
- 格式:
domain
- 说明:域名
-
password3
说明:强等强度密码(在通用密码规则的基础上,必须包含大小写字母、数字和特殊字符)。
Code Block language 示例:
xxx.yyy(首位必须为字母)
Code Block language go func ExampleValidatorExample_Rule_DomainPassword3() { type BizReq struct { Domain1Password1 string `v:"domainpassword3"` Domain2Password2 string `v:"domainpassword3"` Domain3Password3 string `v:"domainpassword3"` Domain4 string `v:"domain"` } var ( ctx = context.Background() req = BizReq{ Domain1Password1: "goframe.orgGoframe123#", Domain2Password2: "a.b",gofra", // error length between 6 and 18 Domain3Password3: "goframe#org", Domain4: "1a.2b",Goframe123", // error must contain lower and upper letters, numbers and special chars. } ) if err := g.Validator().CheckStructData(req).Run(ctx, req); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: // The Domain3Password2 value `gofra` mustis benot a valid domainpassword format; // The Domain4Password3 value `Goframe123` mustis benot a valid domainpassword format }
size
postcode
- 格式:
size:size
postcode
说明:大中国区邮政编码规则。说明:参数长度为
size
(长度参数为整形),注意底层使用Unicode
计算长度,因此中文一个汉字占1
个长度单位。Code Block language go func ExampleValidatorExample_Rule_SizePostcode() { type BizReq struct { Size1Postcode1 string `v:"size:10"postcode"` Postcode2 string `v:"postcode"` Size2Postcode3 string `v:"size:5postcode"` } var ( ctx = context.Background() req = BizReq{ Size1Postcode1: "goframe欢迎你100000", Size2Postcode2: "goframe10000", // error length must be 6 } ) if err Postcode3: "1000000", // error length must be 6 } ) if err := g.Validator().CheckStructData(req).Run(ctx, req); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: // The Size2 value length must be 5 }
length
Postcode2 value `10000` is not a valid postcode format // The Postcode3 value `1000000` is not a valid postcode format }
resident-id
- 格式: resident-id
说明:公民身份证号码。
- 格式:
length:min,max
说明:参数长度为
min
到max
(长度参数为整形),注意底层使用Unicode
计算长度,因此中文一个汉字占1
个长度单位。Code Block language go func ExampleValidatorExample_Rule_LengthResidentId() { type BizReq struct { Length1ResidentID1 string `v:"length:5,10resident-id"` Length2 string `v:"length:10,15"` } var ( ctx = context.Background() req = BizReq{ Length1ResidentID1: "goframe欢迎你", Length2: "goframe320107199506285482", } ) if err := g.Validator().Data(req).CheckStructRun(ctx, req); err != nil { fmt.Print(err) } // Output: // The Length2ResidentID1 value length`320107199506285482` is mustnot bea betweenvalid 10resident andid 15number }
bank-
lengthcard
- 格式:
min-length:min
bank-card 说明:大中国区银行卡号校验。说明:参数长度最小为
min
(长度参数为整形),注意底层使用Unicode
计算长度,因此中文一个汉字占1
个长度单位。Code Block language go func ExampleValidatorExample_Rule_MinLengthBankCard() { type BizReq struct { MinLength1BankCard1 string `v:"minbank-length:10card"` } MinLength2 string `v:"min-length:8"` } var ( var ( ctx = context.Background() req = BizReq{ MinLength1BankCard1: "goframe欢迎你6225760079930218", MinLength2: "goframe", } ) if err := g.Validator().CheckStructData(req).Run(ctx, req); err != nil { fmt.Print(err) } // Output: // The MinLength2BankCard1 value length`6225760079930218` mustis benot equala orvalid greaterbank thancard 8number }
max-length
qq
- 格式:
max-length:max
qq
说明:腾讯QQ号码规则。说明:参数长度最大为
max
(长度参数为整形),注意底层使用Unicode
计算长度,因此中文一个汉字占1
个长度单位。Code Block language go func ExampleValidatorExample_Rule_MaxLengthQQ() { type BizReq struct { MaxLength1QQ1 string `v:"max-length:10"qq"` QQ2 string `v:"qq"` MaxLength2QQ3 string `v:"max-length:5qq"` } var ( ctx = context.Background() req = BizReq{ MaxLength1QQ1: "goframe欢迎你389961817", MaxLength2QQ2: "9999", // error >= 10000 QQ3: "goframe514258412a", // error all number } ) if err := g.Validator().Data(req).CheckStructRun(ctx, req); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: // The MaxLength2QQ2 value length must be equal or lesser than 5 }
between
`9999` is not a valid QQ number // The QQ3 value `514258412a` is not a valid QQ number }
ip
- 格式:
ip
说明:
IPv4/IPv6
地址。- 格式:
between:min,max
说明:参数大小为
min
到max
(支持整形和浮点类型参数)。Code Block language go func ExampleValidatorExample_Rule_BetweenIP() { type BizReq struct { Age1 int IP1 string `v:"between:1,100ip"` Age2 int IP2 string `v:"between:1,100ip"` Score1IP3 float32string `v:"between:0.0,10.0ip"` Score2IP4 float32string `v:"between:0.0,10.0ip"` } var ( ctx = context.Background() req = BizReq{ Age1IP1: 50"127.0.0.1", Age2IP2: 101"fe80::812b:1158:1f43:f0d1", Score1IP3: 9.8, Score2: -0.5"520.255.255.255", // error >= 10000 IP4: "ze80::812b:1158:1f43:f0d1", } ) if err := g.Validator().CheckStructData(req).Run(ctx, req); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: // The Age2IP3 value must be between 1 and 100;`520.255.255.255` is not a valid IP address // The Score2IP4 value must be between 0 and 10 `ze80::812b:1158:1f43:f0d1` is not a valid IP address }
min
ipv4
- 格式:
min:min
ipv4
说明:
IPv4
地址。Code Block 说明:参数大小最小为
min
(支持整形和浮点类型参数)。Code Block language go func ExampleValidatorExample_Rule_MinIPV4() { type BizReq struct { Age1IP1 string int `v:"min:100ipv4"` Age2IP2 string int `v:"min:100"` Score1 float32 `v:"min:10.0"` Score2 float32 `v:"min:10.0"` ipv4"` } var ( ctx = context.Background() req = BizReq{ Age1IP1: 50"127.0.0.1", Age2: 101, Score1: 9.8, Score2: 10.1IP2: "520.255.255.255", } ) if err := g.Validator().CheckStructData(req).Run(ctx, req); err != nil { fmt.Print(err) } // Output: // The Age1IP2 value must be equal or greater than 100; The Score1 value must be equal or greater than 10 }
max
`520.255.255.255` is not a valid IPv4 address }
ipv6
- 格式:
ipv6
说明:
IPv6
地址。- 格式:
max:max
说明:参数大小最大为
max
(支持整形和浮点类型参数)。Code Block language go func ExampleValidatorExample_Rule_MaxIPV6() { type BizReq struct { Age1 int IP1 string `v:"max:100ipv6"` Age2 int IP2 string `v:"max:100ipv6"` } Score1 float32 `v:"max:10.0"` Score2 float32 `v:"max:10.0"` } var ( var ( ctx = context.Background() req = BizReq{ Age1IP1: 99"fe80::812b:1158:1f43:f0d1", Age2: 101, Score1: 9.9, Score2: 10.1IP2: "ze80::812b:1158:1f43:f0d1", } ) if err := g.Validator().Data(req).CheckStructRun(ctx, req); err != nil { fmt.Print(err) } // Output: // The Age2IP2 value must be equal or lesser than 100; The Score2 value must be equal or lesser than 10 }
json
`ze80::812b:1158:1f43:f0d1` is not a valid IPv6 address }
mac
- 格式:
mac
说明:
MAC
地址。- 格式:
json
说明:判断数据格式为
JSON
Code Block language go func ExampleValidatorExample_Rule_JsonMac() { type BizReq struct { Json1Mac1 string `v:"jsonmac"` Json2Mac2 string `v:"jsonmac"` } var ( ctx = context.Background() req = BizReq{ Json1Mac1: "{\"name\":\"goframe\",\"author\":\"郭强\"}", Json2: "{\"name\":\"goframe\",\"author\":\"郭强\",\"test\"}", } ) if err := g.Validator().CheckStruct(ctx, req4C-CC-6A-D6-B1-1A", Mac2: "Z0-CC-6A-D6-B1-1A", } ) if err := g.Validator().Data(req).Run(ctx); err != nil { fmt.Print(err) } // Output: // The Json2Mac2 value must be`Z0-CC-6A-D6-B1-1A` is not a valid JSONMAC stringaddress }
integer
url
- 格式:
integer
url
- 说明:URL
示例:支持以
http,https,ftp,file
开头的地址。说明:整数(正整数或者负整数)。Code Block language go func ExampleValidatorExample_Rule_IntegerUrl() { type BizReq struct { IntegerURL1 string `v:"integerurl"` Float URL2 string `v:"integerurl"` Str URL3 string `v:"integerurl"` } var ( ctx = context.Background() req = BizReq{ IntegerURL1: "100http://goframe.org", FloatURL2: "10.0"ftp://goframe.org", StrURL3: "ws://goframe.org", } ) if err := g.Validator().CheckStructData(req).Run(ctx, req); err != nil { fmt.Print(err) } // Output: // The FloatURL3 value must be an integer; The Str value must be an integer }
float
`ws://goframe.org` is not a valid URL address }
domain
- 格式:
domain
- 说明:域名
示例:域名规则。
xxx.yyy
(首位必须为字母)。- 格式:
float
说明:浮点数
Code Block language go func ExampleValidatorExample_Rule_FloatDomain() { type BizReq struct { IntegerDomain1 string `v:"floatdomain"` FloatDomain2 string `v:"domain"` Domain3 string `v:"floatdomain"` Str Domain4 string `v:"floatdomain"` } var ( ctx = context.Background() req = BizReq{ IntegerDomain1: "100goframe.org", FloatDomain2: "10a.0b", StrDomain3: "goframe"goframe#org", Domain4: "1a.2b", } ) if err := g.Validator().Data(req).CheckStructRun(ctx, req); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: // The Str Domain3 value `goframe#org` is not a valid domain format // The Domain4 value must be`1a.2b` is not a valid domain floatformat }
boolean
size
- 格式:
size:
boolean
size
说明:参数长度为
size
(长度参数为整形),注意底层使用Unicode
计算长度,因此中文一个汉字占1
个长度单位。Code Block language go func Example_Rule_Size
说明:布尔值(
1
,true
,on
,yes
为true
|0
,false
,off
,no
,""
为false
)。Code Block language go func ExampleValidator_Boolean() { type BizReq struct { BooleanSize1 boolstring `v:"booleansize:10"` IntegerSize2 intstring `v:"booleansize:5"` } Floatvar ( ctx float32 `v:"boolean"` Str1 string `v:"boolean"` Str2 string `v:"boolean"` Str3 string `v:"boolean"` } = context.Background() req = BizReq{ Size1: "goframe欢迎你", Size2: "goframe", } ) if err := g.Validator().Data(req).Run(ctx); err != nil { fmt.Print(err) } // Output: // The Size2 value `goframe` length must be 5 }
length
- 格式:
length:min,max
说明:参数长度为
min
到max
(长度参数为整形),注意底层使用Unicode
计算长度,因此中文一个汉字占1
个长度单位。Code Block language go func Example_Rule_Length() { type BizReq struct { Length1 string `v:"length:5,10"` Length2 string `v:"length:10,15"` } var ( ctx = context.Background() req = BizReq{ Length1: "goframe欢迎你", Length2: "goframe", } ) if err := g.Validator().Data(req).Run(ctx); err != nil { fmt.Print(err) } // Output: // The Length2 value `goframe` length must be between 10 and 15 }
min-length
- 格式:
min-length:min
说明:参数长度最小为
min
(长度参数为整形),注意底层使用Unicode
计算长度,因此中文一个汉字占1
个长度单位。Code Block language go func Example_Rule_MinLength() { type BizReq struct { MinLength1 string `v:"min-length:10"` MinLength2 string `v:"min-length:8"` } var ( ctx = context.Background() req = BizReq{ MinLength1: "goframe欢迎你", MinLength2: "goframe", } ) if err := g.Validator().Data(req).Run(ctx); err != nil { fmt.Print(err) } // Output: // The MinLength2 value `goframe` length must be equal or greater than 8 }
max-length
- 格式:
max-length:max
说明:参数长度最大为
max
(长度参数为整形),注意底层使用Unicode
计算长度,因此中文一个汉字占1
个长度单位。Code Block language go func Example_Rule_MaxLength() { type BizReq struct { MaxLength1 string `v:"max-length:10"` MaxLength2 string `v:"max-length:5"` } var ( ctx = context.Background() req = BizReq{ MaxLength1: "goframe欢迎你", MaxLength2: "goframe", } ) if err := g.Validator().Data(req).Run(ctx); err != nil { fmt.Print(err) } // Output: // The MaxLength2 value `goframe` length must be equal or lesser than 5 }
between
- 格式:
between:min,max
说明:参数大小为
min
到max
(支持整形和浮点类型参数)。Code Block language go func Example_Rule_Between() { type BizReq struct { Age1 int `v:"between:1,100"` Age2 int `v:"between:1,100"` Score1 float32 `v:"between:0,10"` Score2 float32 `v:"between:0,10"` } var ( ctx = context.Background() req = BizReq{ Age1: 50, Age2: 101, Score1: 9.8, Score2: -0.5, } ) if err := g.Validator().Data(req).Run(ctx); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: // The Age2 value `101` must be between 1 and 100 // The Score2 value `-0.5` must be between 0 and 10 }
min
- 格式:
min:min
说明:参数大小最小为
min
(支持整形和浮点类型参数)。Code Block language go func Example_Rule_Min() { type BizReq struct { Age1 int `v:"min:100"` Age2 int `v:"min:100"` Score1 float32 `v:"min:10"` Score2 float32 `v:"min:10"` } var ( ctx = context.Background() req = BizReq{ Age1: 50, Age2: 101, Score1: 9.8, Score2: 10.1, } ) if err := g.Validator().Data(req).Run(ctx); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: // The Age1 value `50` must be equal or greater than 100 // The Score1 value `9.8` must be equal or greater than 10 }
max
- 格式:
max:max
说明:参数大小最大为
max
(支持整形和浮点类型参数)。Code Block language go func Example_Rule_Max() { type BizReq struct { Age1 int `v:"max:100"` Age2 int `v:"max:100"` Score1 float32 `v:"max:10"` Score2 float32 `v:"max:10"` } var ( ctx = context.Background() req = BizReq{ Age1: 99, Age2: 101, Score1: 9.9, Score2: 10.1, } ) if err := g.Validator().Data(req).Run(ctx); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: // The Age2 value `101` must be equal or lesser than 100 // The Score2 value `10.1` must be equal or lesser than 10 }
json
- 格式:
json
说明:判断数据格式为
JSON
。Code Block language go func Example_Rule_Json() { type BizReq struct { JSON1 string `v:"json"` JSON2 string `v:"json"` } var ( ctx = context.Background() req = BizReq{ JSON1: "{\"name\":\"goframe\",\"author\":\"郭强\"}", JSON2: "{\"name\":\"goframe\",\"author\":\"郭强\",\"test\"}", } ) if err := g.Validator().Data(req).Run(ctx); err != nil { fmt.Print(err) } // Output: // The JSON2 value `{"name":"goframe","author":"郭强","test"}` is not a valid JSON string }
integer
- 格式:
integer
说明:整数(正整数或者负整数)。
Code Block language go func Example_Rule_Integer() { type BizReq struct { Integer string `v:"integer"` Float string `v:"integer"` Str string `v:"integer"` } var ( ctx = context.Background() req = BizReq{ Integer: "100", Float: "10.0", Str: "goframe", } ) if err := g.Validator().Data(req).Run(ctx); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: // The Float value `10.0` is not an integer // The Str value `goframe` is not an integer }
float
- 格式:
float
说明:浮点数。
Code Block language go func Example_Rule_Float() { type BizReq struct { Integer string `v:"float"` Float string `v:"float"` Str string `v:"float"` } var ( ctx = context.Background() req = BizReq{ Integer: "100", Float: "10.0", Str: "goframe", } ) if err := g.Validator().Data(req).Run(ctx); err != nil { fmt.Print(err) } // Output: // The Str value `goframe` is invalid }
boolean
- 格式:
boolean
说明:布尔值(
1
,true
,on
,yes
为true
|0
,false
,off
,no
,""
为false
)。Code Block language go func Example_Rule_Boolean() { type BizReq struct { Boolean bool `v:"boolean"` Integer int `v:"boolean"` Float float32 `v:"boolean"` Str1 string `v:"boolean"` Str2 string `v:"boolean"` Str3 string `v:"boolean"` } var ( ctx = context.Background() req = BizReq{ Boolean: true, Integer: 1, Float: 10.0, Str1: "on", Str2: "", Str3: "goframe", } ) if err := g.Validator().Data(req).Run(ctx); err != nil { fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: // The Float value `10` field must be true or false // The Str3 value `goframe` field must be true or false }
same
- 格式:
same:field
- 说明:参数值必需与
field
字段参数的值相同。 示例:在用户注册时,提交密码
Password
和确认密码Password2
必须相等(服务端校验)。Code Block language go func Example_Rule_Same() { type BizReq struct { Name string `v:"required"` Password string `v:"required|same:Password2"` Password2 string `v:"required"` } var ( ctx = context.Background() req = BizReq{ Name: "gf", Password: "goframe.org", Password2: "goframe.net", } ) if err := g.Validator().Data(req).Run(ctx); err != nil { fmt.Println(err) } // Output: // The Password value `goframe.org` must be the same as field Password2 }
different
- 格式:
different:field
- 说明:参数值不能与
field
字段参数的值相同。 示例:备用邮箱
OtherMailAddr
和邮箱地址MailAddr
必须不相同。Code Block language go func Example_Rule_Different() { type BizReq struct { Name string `v:"required"` MailAddr string `v:"required"` ConfirmMailAddr string `v:"required|different:MailAddr"` } var ( ctx = context.Background() req = BizReq{ Name: "gf", MailAddr: "gf@goframe.org", ConfirmMailAddr: "gf@goframe.org", } ) if err := g.Validator().Data(req).Run(ctx); err != nil { fmt.Println(err) } // Output: // The ConfirmMailAddr value `gf@goframe.org` must be different from field MailAddr }
eq
- 格式:
eq:field
说明:参数值必需与
field
字段参数的值相同。same
规则的别名,功能同same
规则。- 版本:框架版本
>=v2.2.0
Code Block language go func Example_Rule_EQ() { type BizReq struct { Name string `v:"required"` Password string `v:"required|eq:Password2"` Password2 string `v:"required"` } var ( ctx = context.Background() req = BizReq{ Name: "gf", Password: "goframe.org", Password2: "goframe.net", } ) if err := g.Validator().Data(req).Run(ctx); err != nil { fmt.Println(err) } // Output: // The Password value `goframe.org` must be equal to field Password2 value `goframe.net` }
not-eq
- 格式:
not-eq:field
说明:参数值必需与
field
字段参数的值不相同。different
规则的别名,功能同different
规则。- 版本:框架版本
>=v2.2.0
Code Block language go func Example_Rule_NotEQ() { type BizReq struct { Name string `v:"required"` MailAddr string `v:"required"` OtherMailAddr string `v:"required|not-eq:MailAddr"` } var ( ctx = context.Background() req = BizReq{ Name: "gf", MailAddr: "gf@goframe.org", OtherMailAddr: "gf@goframe.org", } ) if err := g.Validator().Data(req).Run(ctx); err != nil { fmt.Println(err) } // Output: // The OtherMailAddr value `gf@goframe.org` must not be equal to field MailAddr value `gf@goframe.org` }
gt
- 格式:
gt:field
说明:参数值必需大于给定字段对应的值。
- 版本:框架版本
>=v2.2.0
Code Block language go func Example_Rule_GT() { type BizReq struct { Value1 int Value2 int `v:"gt:Value1"` Value3 int `v:"gt:Value1"` } var ( ctx = context.Background() req = BizReq{ Value1: 1, Value2: 1, Value3: 2, } ) if err := g.Validator().Data(req).Run(ctx); err != nil { fmt.Println(err.String()) } // Output: // The Value2 value `1` must be greater than field Value1 value `1` }
gte
- 格式:
gte:field
说明:参数值必需大于或等于给定字段对应的值。
- 版本:框架版本
>=v2.2.0
Code Block language go func Example_Rule_GTE() { type BizReq struct { Value1 int Value2 int `v:"gte:Value1"` Value3 int `v:"gte:Value1"` } var ( ctx = context.Background() req = BizReq{ Value1: 2, Value2: 1, Value3: 2, } ) if err := g.Validator().Data(req).Run(ctx); err != nil { fmt.Println(err.String()) } // Output: // The Value2 value `1` must be greater than or equal to field Value1 value `2` }
lt
- 格式:
lt:field
说明:参数值必需小于给定字段对应的值。
- 版本:框架版本
>=v2.2.0
Code Block language go func Example_Rule_LT() { type BizReq struct { Value1 int Value2 int `v:"lt:Value1"` Value3 int `v:"lt:Value1"` } var ( ctx = context.Background() req = BizReq{ BooleanValue1: true2, IntegerValue2: 1, FloatValue3: 10.02, Str1: "on", Str2: "", Str3: "goframe", } ) if err := g.Validator().Data(req).CheckStructRun(ctx, req); err != nil { fmt.PrintPrintln(err.String()) } // Output: // The FloatValue3 value field`2` must be true or false; The Str3 valuelesser than field mustValue1 be true or falsevalue `2` }
same
lte
- 格式:
samelte:field
- 说明:参数值必需与
field
参数的值相同 说明:参数值必需小于或等于给定字段对应的值。
- 版本:框架版本
>=v2.2.0
示例:在用户注册时,提交密码
Password
和确认密码Password2
必须相等(服务端校验)。Code Block language go func ExampleValidatorExample_Rule_SameLTE() { type BizReq struct { Name string `v:"required"`Value1 int PasswordValue2 int string `v:"required|samelte:Password2Value1"` Password2Value3 stringint `v:"requiredlte:Value1"` } var ( ctx = context.Background() req = BizReq{ NameValue1: "gf"1, PasswordValue2: "goframe.org"1, Password2Value3: "goframe.net"2, } ) if err := g.Validator().Data(req).CheckStructRun(ctx, req); err != nil { fmt.Println(err.String()) } // Output: // The Value3 Passwordvalue value`2` must be lesser than theor sameequal asto field Value1 value Password2`1` }
different
in
- 格式:
different:field
- 说明:参数值不能与
field
参数的值相同 -
in:value1,value2,...
- 说明:参数值应该在
value1,value2,...
中(字符串匹配)。 示例:性别字段
Gender
的值必须在0/1/2
中。示例:备用邮箱OtherMailAddr
和邮箱地址MailAddr
必须不相同。Code Block language go func ExampleValidatorExample_Rule_DifferentIn() { type BizReq struct { NameID uint string `v:"required" dc:"Your Id"` MailAddr Name string `v:"required" dc:"Your name"` OtherMailAddr string `v:"required|different:MailAddrGender uint `v:"in:0,1,2" dc:"0:Secret;1:Male;2:Female"` } var ( ctx = context.Background() req = BizReq{ NameID: "gf"1, MailAddr: "gf@goframe.orgName: "test", OtherMailAddr: "gf@goframe.org"Gender: 3, } ) if err := g.Validator().CheckStructData(req).Run(ctx, req); err != nil { fmt.Println(err) } // Output: // The OtherMailAddrGender value `3` mustis benot differentin fromacceptable field MailAddrrange: 0,1,2 }
not-in
- 格式:
not-in:value1,value2,...
- 说明:参数值应该在说明:参数值不应该在
value1,value2,...
中(字符串匹配)中(字符串匹配)。 示例:无效索引
InvalidIndex
的值必须不在-1/
示例:性别字段Gender
的值必须在0/1/2
中。Code Block language go func ExampleValidatorExample_Rule_InNotIn() { type BizReq struct { IdID uint `v:"required" dc:"Your Id"` Name string `v:"required" dc:"Your name"` Gender InvalidIndex uint `v:"not-in:0,-1,2" dc:"0:Secret;1:Male;2:Female0,1"` } var ( ctx = context.Background() req = BizReq{ IdID: 1, Name: "test", GenderInvalidIndex: 31, } ) if err := g.Validator().CheckStructData(req).Run(ctx, req); err != nil { fmt.Println(err) } // Output: // The GenderInvalidIndex value `1` ismust not be in acceptable rangerange: -1,0,1 }
not-in
regex
- 格式:
not-in:value1,value2,...
- 说明:参数值不应该在
value1,value2,...
中(字符串匹配) -
regex:pattern
说明:参数值应当满足正则匹配规则
pattern
示例:无效索引InvalidIndex
的值必须不在-1/0/1
中。Code Block language go func ExampleValidatorExample_Rule_NotInRegex() { type BizReq struct { Id uint type BizReq struct { Regex1 string `v:"required" dc:"Your Idregex:[1-9][0-9]{4,14}"` Name Regex2 string `v:"required" dc:"Your name"regex:[1-9][0-9]{4,14}"` InvalidIndex uintRegex3 string `v:"not-inregex:-1,0,1[1-9][0-9]{4,14}"` } var ( ctx = context.Background() req = BizReq{ IdRegex1: 1"1234", NameRegex2: "test01234", InvalidIndexRegex3: 1"10000", } ) if err := g.Validator().Data(req).CheckStructRun(ctx, req); err != nil { fmt.Print(gstr.PrintlnJoin(err.Strings(), "\n")) } // Output: // The InvalidIndex value is not in acceptable range }Regex1 value `1234` must be in regex of: [1-9][0-9]{4,14} // The Regex2 value `01234` must be in regex of: [1-9][0-9]{4,14} }
not-regex
- 格式:
not-regex:pattern
说明:参数值不应当满足正则匹配规则
pattern
。- 版本:框架版本
>=v2.2.0
说明:参数值应当满足正则匹配规则
pattern
Code Block language go func ExampleValidatorExample_Rule_RegexNotRegex() { type BizReq struct { Regex1 string `v:"regex:[1-9][0-9]{4,14}"` Regex2Regex1 string `v:"regex:[1-9][0-9]\\d{4,14}"` Regex3Regex2 string `v:"not-regex:[1-9][0-9]\\d{4,14}"` } var ( ctx = context.Background() req = BizReq{ Regex1: "1234", Regex2: "012341234", Regex3: "10000", } ) if err := g.Validator().CheckStructData(req).Run(ctx, req); err != nil { fmt.Print(gstr.PrintlnJoin(err.Strings(), "\n")) } // Output: // The Regex1Regex2 value is invalid; The Regex2 value is invalid`1234` should not be in regex of: \d{4} }
Panel | ||
---|---|---|
| ||
|