Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

GoFrame框架校验组件内置了数十项常用的校验规则,校验组件是开发者最频繁使用的框架核心组件之一。

Note

校验规则涉及到联合校验的场景时,规则中关联的参数名称会自动按照不区分大小写且忽略特殊字符的形式进行智能匹配。

修饰规则

修饰规则本身不做任何的校验逻辑,而是修改功能规则的实现逻辑。

bail

  • 格式:bail
  • 说明:只要后续的多个校验中有一个规则校验失败则停止校验并立即返回校验结果。
  • 示例:

    Code Block
    languagego
    func Example_Rule_Bail() {
    	type BizReq struct {
    		Account   string `v:"bail|required|length:6,16|same:QQ"`
    		QQ        string
    		Password  string `v:"required|same:Password2"`
    		Password2 string `v:"required"`
    	}
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Account:   "gf",
    			QQ:        "123456",
    			Password:  "goframe.org",
    			Password2: "goframe.org",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Println(err)
    	}
    
    	// output:
    	// The Account value `gf` length must be between 6 and 16
    }


ci

  • 格式: ci
  • 说明:字段值比较在默认情况下为区分大小写严格匹配比较,通过Case Insensitive,可以设置对于需要比较值的规则字段为不区分大小写。如:same, different, in, not-in等。
  • 示例:

    Code Block
    languagego
    func Example_Rule_CaseInsensitive() {
    	type BizReq struct {
    		Account   string `v:"required"`
    		Password  string `v:"required|ci|same:Password2"`
    		Password2 string `v:"required"`
    	}
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Account:   "gf",
    			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:
    }
功能规则

foreach

功能规则实现特定的校验逻辑,框架内置了非常丰富强大的内置校验规则。
  • 格式:foreach
required
  • 说明:将待检验的参数作为数组遍历,并将后一个校验规则应用于数组中的每一项。
  • 格式: required
  • 说明:必需参数,除了支持常见的字符串,也支持Slice/Map类型。
  • 示例:姓名字段Name为必需参数必需不能为空。

  • 示例:

    Code Block
    languagego
    func Example_Rule_
  • Required
  • Foreach() {
    	type BizReq struct {
    		
  • ID uint
  • Value1 []int `v:"
  • required
  • foreach|in:1,2,3"`
    		
  • Name
  • Value2 
  • string
  • []int `v:"
  • required
  • foreach|in:1,2,3"`
    	}
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			
  • ID
  • Value1: []int{1, 2, 3},
    			Value2: []int{3, 4, 5},
    		}
    	)
    	if err := g.Validator().Bail().Data(req).Run(ctx); err != nil {
    		fmt.
  • Print
  • Println(err.String())
    	}
    
    	// Output:
    	// The Value2 
  • Name
  • value 
  • field
  • `4` is
  • required
  •  not in acceptable range: 1,2,3
    }


功能规则

功能规则实现特定的校验逻辑,框架内置了非常丰富强大的内置校验规则。

required

-if

  • 格式: required-if:field,value,...
  • 说明:必需参数(当任意所给定字段值与所给值相等时,即:当field字段的值为value时,当前验证字段为必须参数)。多个字段以,号分隔。
  • 示例:当Gender字段为1WifeName字段必须不为空, 当Gender字段为2HusbandName字段必须不为空。
  • 说明:必需参数,除了支持常见的字符串,也支持Slice/Map类型。
  • 示例:姓名字段Name为必需参数必需不能为空。

    Code Block
    languagego
    func Example_Rule_
  • RequiredIf
  • Required() {
    	type BizReq struct {
    		ID
  •    
  • uint   `v:"required"
  • dc:"Your ID"
  • `
    		Name
  •  string `v:"required
  • " dc:
  • "
  • Your name"
  • `
    	}
    	
  • Gender
  • var (
    		ctx = context.Background()
    		req = BizReq{
    			ID: 1,
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(err)
    	}
    
    	// Output:
    	// The Name field is required
    }


required-if

  • 格式: required-if:field,value,...
  • 说明:必需参数(当任意所给定字段值与所给值相等时,即:当field字段的值为value时,当前验证字段为必须参数)。多个字段以,号分隔。
  • 示例:当Gender字段为1WifeName字段必须不为空, 当Gender字段为2HusbandName字段必须不为空。

    Code Block
    languagego
    func Example_Rule_RequiredIf() {
    	type BizReq struct {
    		ID          uint   `v:"required" dc:"Your ID"`
    		Name        string `v:"required" dc:"Your name"`
    		Gender      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:     1,
    			Name:   "test",
    			Gender: 1,
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Println(err)
    	}
    
    	// Output:
    	// The WifeName field is required
    }


required-unless

  • 格式: required-unless:field,value,...
  • 说明:必需参数(当所给定字段值与所给值都不相等时,即:当field字段的值不为value时,当前验证字段为必须参数)。多个字段以,号分隔。
  • 示例:当Gender不等于0Gender不等于2时,WifeName必须不为空;当Id 不等于0 Gender 不等于2时, HusbandName 必须不为空。

    Code Block
    languagego
    func Example_Rule_RequiredUnless() {
    	type BizReq struct {
    		ID          uint   `v:"required" dc:"Your ID"`
    		Name        string `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,2"`
    	}
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			ID:     1,
    			Name:   "test",
    			Gender: 1,
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Println(err)
    	}
    
    	// Output:
    	// The WifeName field is required; The HusbandName field is required
    }


required-with

  • 格式: required-with:field1,field2,...
  • 说明:必需参数(当所给定任意字段值其中之一不为空时)。
  • 示例:当WifeName不为空时,HusbandName必须不为空。

    Code Block
    languagego
    func Example_Rule_RequiredWith() {
    	type BizReq struct {
    		ID          uint   `v:"required" dc:"Your ID"`
    		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{
    			ID:       1,
    			Name:     "test",
    			Gender:   1,
    			WifeName: "Ann",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Println(err)
    	}
    
    	// Output:
    	// The HusbandName field is required
    }


required-with-all

  • 格式: required-with-all:field1,field2,...
  • 说明:必须参数(当所给定所有字段值全部都不为空时)。
  • 示例:当Id,Name,Gender,WifeName全部不为空时,HusbandName必须不为空。

    Code Block
    languagego
    func Example_Rule_RequiredWithAll() {
    	type BizReq struct {
    		ID          uint   `v:"required" dc:"Your ID"`
    		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-all:Id,Name,Gender,WifeName"`
    	}
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			ID:       1,
    			Name:     "test",
    			Gender:   1,
    			WifeName: "Ann",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Println(err)
    	}
    
    	// Output:
    	// The HusbandName field is required
    }


required-without

  • 格式: required-without:field1,field2,...
  • 说明:必需参数(当所给定任意字段值其中之一为空时)。
  • 示例:当IdWifeName为空时,HusbandName必须不为空。

    Code Block
    languagego
    func Example_Rule_RequiredWithout() {
    	type BizReq struct {
    		ID          uint   `v:"required" dc:"Your ID"`
    		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:Id,WifeName"`
    	}
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			ID:     1,
    			Name:   "test",
    			Gender: 1,
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Println(err)
    	}
    
    	// Output:
    	// The HusbandName field is required
    }


required-without-all

  • 格式: required-without-all:field1,field2,...
  • 说明:必须参数(当所给定所有字段值全部都为空时)。
  • 示例:当IdWifeName都为空时,HusbandName必须不为空。

    Code Block
    languagego
    func Example_Rule_RequiredWithoutAll() {
    	type BizReq struct {
    		ID          uint   `v:"required" dc:"Your ID"`
    		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-all:Id,WifeName"`
    	}
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Name:   "test",
    			Gender: 1,
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Println(err)
    	}
    
    	// Output:
    	// The HusbandName field is required
    }

     

date

  • 格式: date
  • 说明:参数为常用日期类型,日期之间支持的连接符号-/.,也支持不带连接符号的8位长度日期,格式如: 2006-01-02, 2006/01/02, 2006.01.02, 20060102
  • 示例:

    Code Block
    languagego
    func Example_Rule_Date() {
    	type BizReq struct {
    		Date1 string `v:"date"`
    		Date2 string `v:"date"`
    		Date3 string `v:"date"`
    		Date4 string `v:"date"`
    		Date5 string `v:"date"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Date1: "2021-10-31",
    			Date2: "2021.10.31",
    			Date3: "2021-Oct-31",
    			Date4: "2021 Octa 31",
    			Date5: "2021/Oct/31",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The Date3 value `2021-Oct-31` is not a valid date
    	// The Date4 value `2021 Octa 31` is 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
    languagego
    func Example_Rule_Datetime() {
    	type BizReq struct {
    		Date1 string `v:"datetime"`
    		Date2 string `v:"datetime"`
    		Date3 string `v:"datetime"`
    		Date4 string `v:"datetime"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Date1: "2021-11-01 23:00:00",
    			Date2: "2021-11-01 23:00",     // error
    			Date3: "2021/11/01 23:00:00",  // error
    			Date4: "2021/Dec/01 23:00:00", // error
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The Date2 value `2021-11-01 23:00` is not a valid datetime
    	// The Date3 value `2021/11/01 23:00:00` is not a valid datetime
    	// The Date4 value `2021/Dec/01 23:00:00` is not a valid datetime
    }


date-format

  • 格式: date-format:format
  • 说明:判断日期是否为指定的日期/时间格式,format参数格式为gtime日期格式(可以包含日期及时间),格式说明参考章节:gtime模块
  • 示例:date-format:Y-m-d H:i:s

    Code Block
    languagego
    func Example_Rule_DateFormat() {
    	type BizReq struct {
    		Date1 string `v:"date-format:Y-m-d"`
    		Date2 string `v:"date-format:Y-m-d"`
    		Date3 string `v:"date-format:Y-m-d H:i:s"`
    		Date4 string `v:"date-format:Y-m-d H:i:s"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Date1: "2021-11-01",
    			Date2: "2021-11-01 23:00", // error
    			Date3: "2021-11-01 23:00:00",
    			Date4: "2021-11-01 23:00", // error
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The Date2 value `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
  • 说明:判断给定的日期/时间是否在指定字段的日期/时间之前。

    Code Block
    languagego
    func Example_Rule_Before() {
    	type BizReq struct {
    		Time1 string `v:"before:Time3"`
    		Time2 string `v:"before:Time3"`
    		Time3 string
    	}
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Time1: "2022-09-02",
    			Time2: "2022-09-03",
    			Time3: "2022-09-03",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Println(err.String())
    	}
    
    	// Output:
    	// The Time2 value `2022-09-03` must be before field Time3 value `2022-09-03`
    }


before_equal

  • 格式: before_equal:field
  • 说明:判断给定的日期/时间是否在指定字段的日期/时间之前,或者与指定字段的日期/时间相等。

    Code Block
    languagego
    func Example_Rule_BeforeEqual() {
    	type BizReq struct {
    		Time1 string `v:"before-equal:Time3"`
    		Time2 string `v:"before-equal:Time3"`
    		Time3 string
    	}
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Time1: "2022-09-02",
    			Time2: "2022-09-01",
    			Time3: "2022-09-01",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The Time1 value `2022-09-02` must be before or equal to field Time3
    }


after

  • 格式: after:field
  • 说明:判断给定的日期/时间是否在指定字段的日期/时间之后。

    Code Block
    languagego
    func Example_Rule_After() {
    	type BizReq struct {
    		Time1 string
    		Time2 string `v:"after:Time1"`
    		Time3 string `v:"after:Time1"`
    	}
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Time1: "2022-09-01",
    			Time2: "2022-09-01",
    			Time3: "2022-09-02",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Println(err.String())
    	}
    
    	// Output:
    	// The Time2 value `2022-09-01` must be after field Time1 value `2022-09-01`
    }


after_equal

  • 格式: after_equal:field
  • 说明:判断给定的日期/时间是否在指定字段的日期/时间之后,或者与指定字段的日期/时间相等。


    Code Block
    languagego
    func Example_Rule_AfterEqual() {
    	type BizReq struct {
    		Time1 string
    		Time2 string `v:"after-equal:Time1"`
    		Time3 string `v:"after-equal:Time1  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{
    			IDTime1:     1"2022-09-02",
    			NameTime2:   "test2022-09-01",
    			GenderTime3: 1"2022-09-02",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.PrintlnPrint(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The WifeName field is required
    }

required-unless

  •  The Time2 value `2022-09-01` must be after or equal to field Time1 value `2022-09-02`
    }


array

  • 格式: array
  • 说明:判断给定的参数是否数组格式。如果给定的参数为JSON数组字符串,也将检验通过。

  • 格式: required-unless:field,value,...
  • 说明:必需参数(当所给定字段值与所给值都不相等时,即:当field字段的值不为value时,当前验证字段为必须参数)。多个字段以,号分隔。
  • 示例:当Gender不等于0Gender不等于2时,WifeName必须不为空;当Id 不等于0 Gender 不等于2时, HusbandName 必须不为空。

    Code Block
    languagego
    func Example_Rule_RequiredUnlessArray() {
    	type BizReq struct {
    		ID        Value1 string  uint   `v:"required" dc:"Your ID"array"`
    		Name        string `v:"required" dc:"Your name"`
    		Gender      uintValue2 string   `v:"in:0,1,2" dc:"0:Secret;1:Male;2:Female"array"`
    		WifeNameValue3  string  string `v:"required-unless:gender,0,gender,2array"`
    		HusbandNameValue4 []string `v:"required-unless:id,0,gender,2array"`
    	}
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			IDValue1:     1"1,2,3",
    			NameValue2:   "test"[]",
    			Value3: "[1,2,3]",
    			GenderValue4: 1[]string{},
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.PrintlnPrint(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The WifeName fieldValue1 value `1,2,3` is required;not Theof HusbandNamevalid fieldarray is requiredtype
    }

required-with


email

  • 格式:email
  • 说明:EMAIL邮箱地址格式。

  • 格式: required-with:field1,field2,...
  • 说明:必需参数(当所给定任意字段值其中之一不为空时)。
  • 示例:当WifeName不为空时,HusbandName必须不为空。

    Code Block
    languagego
    func Example_Rule_RequiredWithEmail() {
    	type BizReq struct {
    		ID          uint   `v:"required" dc:"Your ID"`
    		Name        string `v:"required" dc:"Your name"`
    		Gender      uint  	MailAddr1 string `v:"in:0,1,2" dc:"0:Secret;1:Male;2:Femaleemail"`
    		MailAddr2 string `v:"email"`
    		WifeNameMailAddr3    stringstring `v:"email"`
    		HusbandNameMailAddr4 string `v:"required-with:WifeNameemail"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			IDMailAddr1:       1"gf@goframe.org",
    			NameMailAddr2:     "testgf@goframe", // error
    			GenderMailAddr3:   1"gf@goframe.org.cn",
    			WifeNameMailAddr4: "Anngf#goframe.org", // error
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Println(err.Print(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The HusbandName field is required
    }

required-with-all

  •  MailAddr2 value `gf@goframe` is not a valid email address
    	// The MailAddr4 value `gf#goframe.org` is not a valid email address
    }


phone

  • 格式:phone
  • 说明:大中国区手机号格式。

  • 格式: required-with-all:field1,field2,...
  • 说明:必须参数(当所给定所有字段值全部都不为空时)。
  • 示例:当Id,Name,Gender,WifeName全部不为空时,HusbandName必须不为空。

    Code Block
    languagego
    func Example_Rule_RequiredWithAllPhone() {
    	type BizReq struct {
    		ID          uint   `v:"required" dc:"Your ID"`
    		Name       
    	type BizReq struct {
    		PhoneNumber1 string `v:"required" dc:"Your name"phone"`
    		Gender      uint  PhoneNumber2 string `v:"in:0,1,2" dc:"0:Secret;1:Male;2:Female"phone"`
    		WifeNamePhoneNumber3    stringstring `v:"phone"`
    		HusbandNamePhoneNumber4 string `v:"required-with-all:Id,Name,Gender,WifeNamephone"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			IDPhoneNumber1: "13578912345",
    			PhoneNumber2: "11578912345", // error 11x not 1,exist
    			NamePhoneNumber3:     "test17178912345",
    			Gender:   1, // error 171 not exit
    			WifeNamePhoneNumber4: "Ann1357891234",  // error len must be 11
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.PrintlnJoin(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The HusbandName field is required
    }

required-without

  •  PhoneNumber2 value `11578912345` is not a valid 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位数字都可以通过验证。可用于非严格的业务场景。

  • 格式: required-without:field1,field2,...
  • 说明:必需参数(当所给定任意字段值其中之一为空时)。
  • 示例:当IdWifeName为空时,HusbandName必须不为空。

    Code Block
    languagego
    func Example_Rule_RequiredWithoutPhoneLoose() {
    	type BizReq struct {
    		ID          uint   `v:"required" dc:"Your ID"`
    		Name        PhoneNumber1 string `v:"required" dc:"Your name"`
    		Gender      uint   `v:"in:0,1,2" dc:"0:Secret;1:Male;2:Femalephone-loose"`
    		WifeNamePhoneNumber2 string `v:"phone-loose"`
    		PhoneNumber3  stringstring `v:"phone-loose"`
    		HusbandNamePhoneNumber4 string `v:"required-without:Id,WifeNamephone-loose"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			PhoneNumber1: "13578912345",
    		ID	PhoneNumber2: "11578912345", // error 11x 1,not exist
    			NamePhoneNumber3:   "test17178912345",
    			GenderPhoneNumber4: 1,"1357891234", // error len must be 11
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.PrintlnPrint(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// Output:
    	// The PhoneNumber2 value `11578912345` is invalid
    	// The PhoneNumber4 HusbandNamevalue field`1357891234` is requiredinvalid
    }
required-without-all

telephone

  • 格式: required-without-all:field1,field2,...
  • 说明:必须参数(当所给定所有字段值全部都为空时)。
  • telephone
  • 说明:大中国区座机电话号码,”XXXX-XXXXXXX”、”XXXX-XXXXXXXX”、”XXX-XXXXXXX”、”XXX-XXXXXXXX”、”XXXXXXX”、”XXXXXXXX”。

    示例:当IdWifeName都为空时,HusbandName必须不为空。

    Code Block
    languagego
    func Example_Rule_RequiredWithoutAllTelephone() {
    	type BizReq struct {
    		ID          uint   `v:"required" dc:"Your ID"`
    		Name        string `v:"required" dc:"Your name"`
    		Gender      uint  Telephone1 string `v:"in:0,1,2" dc:"0:Secret;1:Male;2:Femaletelephone"`
    		Telephone2 string `v:"telephone"`
    		WifeNameTelephone3    stringstring `v:"telephone"`
    		HusbandNameTelephone4 string `v:"required-without-all:Id,WifeNametelephone"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			NameTelephone1: "010-77542145",
    			Telephone2: "0571-77542145",
    			Telephone3: "test20-77542145", // error
    			GenderTelephone4: 1,"775421451",   // error len must be 7 or 8
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Println(errfmt.Print(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The Telephone3 value `20-77542145` is not a valid telephone number
    	// The Telephone4 HusbandNamevalue field`775421451` is requirednot a valid telephone number
    }
     


passport

date

  • 格式: date
  • 说明:参数为常用日期类型,日期之间支持的连接符号-/.,也支持不带连接符号的8位长度日期,格式如: 2006-01-02, 2006/01/02, 2006.01.02, 20060102
  • passport
  • 说明:通用帐号规则(字母开头,只能包含字母、数字和下划线,长度在6~18之间)。

    示例:

    Code Block
    languagego
    func Example_Rule_DatePassport() {
    	type BizReq struct {
    		Date1Passport1 string `v:"datepassport"`
    		Date2Passport2 string `v:"datepassport"`
    		Date3Passport3 string `v:"datepassport"`
    		Date4 string `v:"date"`
    		Date5Passport4 string `v:"datepassport"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Date1Passport1: "2021-10-31goframe",
    			Date2Passport2: "2021.10.311356666",  // error starting with letter
    			Date3Passport3: "2021-Oct-31",goframe#", // error containing only numbers or underscores
    			Date4Passport4: "2021 Octa 31",
    			Date5: "2021/Oct/31","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 Date3Passport2 value `2021-Oct-31``1356666` is not a valid datepassport format
    	// The Date4Passport3 value `2021 Octa 31``goframe#` is not a valid passport dateformat
    	// The Date5Passport4 value `2021/Oct/31``gf` is not a valid passport dateformat
    }
datetime

password

  • 格式: datetime
  • 说明:参数为常用日期时间类型,其中日期之间支持的连接符号只支持-,格式如: 2006-01-02 12:00:00
  • password
  • 说明:通用密码规则(任意可见字符,长度在6~18之间)。示例:

    Code Block
    languagego
    func Example_Rule_DatetimePassword() {
    	type BizReq struct {
    		Date1Password1 string `v:"datetimepassword"`
    		Date2Password2 string `v:"datetimepassword"`
    		Date3 string `v:"datetime"`
    		Date4 string `v:"datetime"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Date1: "2021-11-01 23:00:00",
    			Date2: "2021-11-01 23:00",     // error
    			Date3: "2021/11/01 23:00:00",  // error			Password1: "goframe",
    			Date4Password2: "2021/Dec/01 23:00:00gofra", // 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 Date2 value `2021-11-01 23:00` is not a valid datetime
    	// The Date3 value `2021/11/01 23:00:00` is not a valid datetime
    	// The Date4 value `2021/Dec/01 23:00:00`Password2 value `gofra` is not a valid password datetimeformat
    }
date-format

password2

  • 格式: date-format:format
  • 说明:判断日期是否为指定的日期/时间格式,format参数格式为gtime日期格式(可以包含日期及时间),格式说明参考章节:gtime模块
  • password2
  • 说明:中等强度密码(在通用密码规则的基础上,要求密码必须包含大小写字母和数字)。

    示例:date-format:Y-m-d H:i:s

    Code Block
    languagego
    func Example_Rule_DateFormatPassword2() {
    	type BizReq struct {
    		Date1Password1 string `v:"date-format:Y-m-dpassword2"`
    		Date2Password2 string `v:"date-format:Y-m-dpassword2"`
    		Date3Password3 string `v:"date-format:Y-m-d H:i:spassword2"`
    		Date4Password4 string `v:"date-format:Y-m-d H:i:spassword2"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Date1Password1: "2021-11-01Goframe123",
    			Date2Password2: "2021-11-01 23:00gofra",      // error length between 6 and 18
    			Date3Password3: "2021-11-01 23:00:00",Goframe",    // error must contain lower and upper letters and numbers.
    			Date4Password4: "2021-11-01 23:00goframe123", // 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 Date2Password3 value `2021-11-01 23:00` does not match the format: Y-m-d`Goframe` is not a valid password format
    	// The Date4Password4 value `2021-11-01 23:00` does not match the format: Y-m-d H:i:s
    }

email

  • `goframe123` is not a valid password format
    }


password3

  • 格式: password3
  • 说明:强等强度密码(在通用密码规则的基础上,必须包含大小写字母、数字和特殊字符)。

  • 格式:email
  • 说明:EMAIL邮箱地址格式。

    Code Block
    languagego
    func Example_Rule_EmailPassword3() {
    	type BizReq struct {
    		MailAddr1Password1 string `v:"emailpassword3"`
    		MailAddr2Password2 string `v:"emailpassword3"`
    		MailAddr3Password3 string `v:"emailpassword3"`
    		MailAddr4 string `v:"email"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			MailAddr1Password1: "gf@goframe.orgGoframe123#",
    			MailAddr2Password2: "gf@goframegofra",      // error
    			MailAddr3: "gf@goframe.org.cn", length between 6 and 18
    			MailAddr4Password3: "gf#goframe.orgGoframe123", // error must contain lower and upper letters, numbers and special chars.
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The MailAddr2Password2 value `gf@goframe``gofra` is not a valid emailpassword addressformat
    	// The MailAddr4Password3 value `gf#goframe.org``Goframe123` is not a valid emailpassword addressformat
    }

phone


postcode

  • 格式: postcode
  • 说明:大中国区邮政编码规则。

  • 格式:phone
  • 说明:大中国区手机号格式。

    Code Block
    languagego
    func Example_Rule_PhonePostcode() {
    	type BizReq struct {
    		PhoneNumber1Postcode1 string `v:"phonepostcode"`
    		PhoneNumber2Postcode2 string `v:"phonepostcode"`
    		PhoneNumber3Postcode3 string `v:"phonepostcode"`
    		PhoneNumber4 string `v:"phone"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			PhoneNumber1: "13578912345",
    			PhoneNumber2: "11578912345", // error 11x not existPostcode1: "100000",
    			PhoneNumber3Postcode2: "1717891234510000",   // error length 171must notbe exit6
    			PhoneNumber4Postcode3: "13578912341000000",  // error lenlength must be 116
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The PhoneNumber2Postcode2 value `11578912345``10000` is not a valid phonepostcode numberformat
    	// The PhoneNumber3Postcode3 value `17178912345``1000000` is not a valid phonepostcode number
    	// The PhoneNumber4 value `1357891234` is not a valid phone number
    }

phone-loose

  • format
    }


resident-id

  • 格式:  resident-id
  • 说明:公民身份证号码。

  • 格式: phone
  • 说明:宽松的手机号验证,只要满足 13、14、15、16、17、18、19开头的11位数字都可以通过验证。可用于非严格的业务场景。

    Code Block
    languagego
    func Example_Rule_PhoneLooseResidentId() {
    	type BizReq struct {
    		PhoneNumber1 string `v:"phone-loose"`
    		PhoneNumber2 string `v:"phone-loose"`
    		PhoneNumber3 string `v:"phone-loose"` {
    		PhoneNumber4ResidentID1 string `v:"phoneresident-looseid"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			PhoneNumber1ResidentID1: "13578912345",
    			PhoneNumber2: "11578912345", // error 11x not exist
    			PhoneNumber3: "17178912345320107199506285482",
    			PhoneNumber4: "1357891234", // error len must be 11
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The PhoneNumber2ResidentID1 value `11578912345``320107199506285482` is invalid
    	// The PhoneNumber4 value `1357891234` is invalid
    }

telephone

  • not a valid resident id number
    }


bank-card

  • 格式:   bank-card
  • 说明:大中国区银行卡号校验。

  • 格式: telephone
  • 说明:大中国区座机电话号码,”XXXX-XXXXXXX”、”XXXX-XXXXXXXX”、”XXX-XXXXXXX”、”XXX-XXXXXXXX”、”XXXXXXX”、”XXXXXXXX”。

    Code Block
    languagego
    func Example_Rule_TelephoneBankCard() {
    	type BizReq struct {
    		Telephone1BankCard1 string `v:"telephone"`
    		Telephone2 string `v:"telephone"`
    		Telephone3 string `v:"telephonebank-card"`
    		Telephone4 string `v:"telephone"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Telephone1BankCard1: "010-77542145",
    			Telephone2: "0571-77542145",
    			Telephone3: "20-77542145", // error
    			Telephone4: "775421451",   // error len must be 7 or 86225760079930218",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The Telephone3BankCard1 value `20-77542145``6225760079930218` is not a valid telephone number
    	// The Telephone4 value `775421451` is not a valid telephone bank card number
    }
passport

qq

  • 格式: passport qq
  • 说明:通用帐号规则(字母开头,只能包含字母、数字和下划线,长度在6~18之间)。说明:腾讯QQ号码规则。

    Code Block
    languagego
    func Example_Rule_PassportQQ() {
    	type BizReq struct {
    		Passport1QQ1 string `v:"passportqq"`
    		Passport2QQ2 string `v:"passportqq"`
    		Passport3QQ3 string `v:"passportqq"`
    		Passport4 string `v:"passport"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Passport1QQ1: "goframe389961817",
    			Passport2QQ2: "13566669999",  // error starting with letter
    			Passport3: "goframe#", // error containing only numbers or underscores>= 10000
    			Passport4QQ3: "gf514258412a",       // error length between 6 and 18all number
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The Passport2QQ2 value `1356666``9999` is not a valid passportQQ formatnumber
    	// The Passport3QQ3 value `goframe#``514258412a` is not a valid passportQQ format
    	// The Passport4 value `gf` is not a valid passport format
    }
password
  • number
    }


ip

  • 格式: password ip
  • 说明:IPv4/IPv6地址。说明:通用密码规则(任意可见字符,长度在6~18之间)。

    Code Block
    languagego
    func Example_Rule_PasswordIP() {
    	type BizReq struct {
    		Password1IP1 string `v:"ip"`
    		IP2 string `v:"ip"`
    		IP3 string `v:"passwordip"`
    		Password2IP4 string `v:"passwordip"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{ = BizReq{
    			IP1: "127.0.0.1",
    			Password1IP2: "goframefe80::812b:1158:1f43:f0d1",
    			Password2IP3: "gofra520.255.255.255", // error length between 6 and 18>= 10000
    			IP4: "ze80::812b:1158:1f43:f0d1",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The Password2 value `gofra` IP3 value `520.255.255.255` is not a valid IP address
    	// The IP4 value `ze80::812b:1158:1f43:f0d1` is not a valid passwordIP formataddress
    }
password2

ipv4

  • 格式: password2 ipv4
  • 说明:IPv4地址。说明:中等强度密码(在通用密码规则的基础上,要求密码必须包含大小写字母和数字)。

    Code Block
    languagego
    func Example_Rule_Password2IPV4() {
    	type BizReq struct {
    		Password1IP1 string `v:"password2ipv4"`
    		Password2IP2 string `v:"password2"`
    		Password3 string `v:"password2"`
    		Password4 string `v:"password2ipv4"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Password1: "Goframe123",
    			Password2: "gofra",      // error length between 6 and 18
    			Password3: "Goframe",    // error must contain lower and upper letters and numbers. BizReq{
    			Password4IP1: "goframe123127.0.0.1", // error must contain lower and upper letters and numbers.
    			IP2: "520.255.255.255",
    		}
    	)
    	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 Password4 value `goframe123`IP2 value `520.255.255.255` is not a valid passwordIPv4 formataddress
    }
password3

ipv6

  • 格式: password3 ipv6
  • 说明:IPv6地址。说明:强等强度密码(在通用密码规则的基础上,必须包含大小写字母、数字和特殊字符)。

    Code Block
    languagego
    func Example_Rule_Password3IPV6() {
    	type BizReq struct {
    		Password1IP1 string `v:"password3ipv6"`
    		Password2IP2 string `v:"password3"`
    		Password3 string `v:"password3ipv6"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Password1IP1: "Goframe123#fe80::812b:1158:1f43:f0d1",
    			Password2IP2: "gofra",      // error length between 6 and 18
    			Password3: "Goframe123", // error must contain lower and upper letters, numbers and special chars.ze80::812b:1158:1f43:f0d1",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The Password2IP2 value `gofra``ze80::812b:1158:1f43:f0d1` is not a valid password format
    	// The Password3 value `Goframe123` is not a valid password formatIPv6 address
    }
postcode

mac

  • 格式: postcode mac
  • 说明:大中国区邮政编码规则。说明:MAC地址。

    Code Block
    languagego
    func Example_Rule_PostcodeMac() {
    	type BizReq struct {
    		Postcode1Mac1 string `v:"postcodemac"`
    		Postcode2Mac2 string `v:"postcodemac"`
    		Postcode3 string `v:"postcode"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Postcode1Mac1: "100000",
    			Postcode2: "10000",   // error length must be 64C-CC-6A-D6-B1-1A",
    			Postcode3Mac2: "1000000", // error length must be 6Z0-CC-6A-D6-B1-1A",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The Postcode2Mac2 value `10000``Z0-CC-6A-D6-B1-1A` is not a valid postcodeMAC format
    	// The Postcode3 value `1000000` is not a valid postcode format
    }

resident-id

  • address
    }


url

  • 格式: url
  • 说明:URL
  • 示例:支持以http,https,ftp,file开头的地址。

  • 格式:  resident-id
  • 说明:公民身份证号码。

    Code Block
    languagego
    func Example_Rule_ResidentIdUrl() {
    	type BizReq struct { struct {
    		URL1 string `v:"url"`
    		URL2 string `v:"url"`
    		ResidentID1URL3 string `v:"resident-idurl"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			URL1: "http://goframe.org",
    			URL2: "ftp://goframe.org",
    		ResidentID1	URL3: "320107199506285482ws://goframe.org",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(err)
    	}
    
    	// Output:
    	// The ResidentID1URL3 value `320107199506285482``ws://goframe.org` is not a valid residentURL id numberaddress
    }
bank-card

domain

  • 格式:   bank-card domain
  • 说明:域名
  • 示例:域名规则。xxx.yyy(首位必须为字母)。说明:大中国区银行卡号校验。

    Code Block
    languagego
    func Example_Rule_BankCard() {
    	type BizReq struct {
    		BankCard1Domain() {
    	type BizReq struct {
    		Domain1 string `v:"domain"`
    		Domain2 string `v:"domain"`
    		Domain3 string `v:"domain"`
    		Domain4 string `v:"bank-carddomain"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Domain1: "goframe.org",
    			BankCard1Domain2: "a.b",
    			Domain3: "goframe#org",
    			Domain4: "62257600799302181a.2b",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The BankCard1Domain3 value `6225760079930218``goframe#org` is not a valid bank card numberdomain format
    	// The Domain4 value `1a.2b` is not a valid domain format
    }
qq

size

  • 格式: size: qqsize
  • 说明:参数长度 size (长度参数为整形),注意底层使用Unicode计算长度,因此中文一个汉字占1个长度单位。说明:腾讯QQ号码规则。

    Code Block
    languagego
    func Example_Rule_QQSize() {
    	type BizReq struct {
    		QQ1Size1 string `v:"qqsize:10"`
    		QQ2Size2 string `v:"qq"`
    		QQ3 string `v:"qqsize:5"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			QQ1Size1: "389961817goframe欢迎你",
    			QQ2Size2: "9999goframe",       // error >= 10000
    			QQ3: "514258412a", // error all number
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The QQ2 value `9999` is not a valid QQ number Output:
    	// The QQ3Size2 value `514258412a``goframe` islength notmust a valid QQ numberbe 5
    }
ip

length

  • 格式: length: ipmin,max
  • 说明:参数长度minmax(长度参数为整形),注意底层使用Unicode计算长度,因此中文一个汉字占1个长度单位。说明:IPv4/IPv6地址。

    Code Block
    languagego
    func Example_Rule_IPLength() {
    	type BizReq struct {
    		IP1Length1 string `v:"ip"`
    		IP2 string `v:"iplength:5,10"`
    		IP3Length2 string `v:"ip"`
    		IP4 string `v:"ip"length:10,15"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			IP1: "127.0.0.1",
    			IP2: "fe80::812b:1158:1f43:f0d1",
    			IP3Length1: "520.255.255.255", // error >= 10000goframe欢迎你",
    			IP4Length2: "ze80::812b:1158:1f43:f0d1goframe",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The IP3Length2 value `520.255.255.255` is not a valid IP address
    	// The IP4 value `ze80::812b:1158:1f43:f0d1` is not a valid IP address
    }

ipv4

  • `goframe` length must be between 10 and 15
    }


min-length

  • 格式: min-length:min
  • 说明:参数长度最小为min(长度参数为整形),注意底层使用Unicode计算长度,因此中文一个汉字占1个长度单位。

  • 格式: ipv4
  • 说明:IPv4地址。

    Code Block
    languagego
    func Example_Rule_IPV4MinLength() {
    	type BizReq struct {
    		IP1MinLength1 string `v:"ipv4min-length:10"`
    		IP2MinLength2 string `v:"ipv4min-length:8"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			IP1MinLength1: "127.0.0.1goframe欢迎你",
    			IP2MinLength2: "520.255.255.255goframe",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(err)
    	}
    
    	// Output:
    	// The IP2MinLength2 value `520.255.255.255` is not a valid IPv4 address
    }

ipv6

  • `goframe` length must be equal or greater than 8
    }


max-length

  • 格式: max-length:max
  • 说明:参数长度最大为max(长度参数为整形),注意底层使用Unicode计算长度,因此中文一个汉字占1个长度单位。

  • 格式: ipv6
  • 说明:IPv6地址。

    Code Block
    languagego
    func Example_Rule_IPV6MaxLength() {
    	type BizReq struct {
    		IP1MaxLength1 string `v:"ipv6max-length:10"`
    		IP2MaxLength2 string `v:"ipv6max-length:5"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			IP1: "fe80::812b:1158:1f43:f0d1	MaxLength1: "goframe欢迎你",
    			IP2MaxLength2: "ze80::812b:1158:1f43:f0d1goframe",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(err)
    	}
    
    	// Output:
    	// The IP2MaxLength2 value `ze80::812b:1158:1f43:f0d1` is not a valid IPv6 address
    }

mac

  • `goframe` length must be equal or lesser than 5
    }


between

  • 格式: between:min,max
  • 说明:参数大小minmax(支持整形和浮点类型参数)。

  • 格式: mac
  • 说明:MAC地址。

    Code Block
    languagego
    func Example_Rule_MacBetween() {
    	type BizReq struct {
    		Mac1 stringAge1   int     `v:"between:1,100"`
    		Age2   int     `v:"between:1,100"`
    		Score1 float32 `v:"macbetween:0.0,10.0"`
    		Mac2Score2 stringfloat32 `v:"macbetween:0.0,10.0"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Age1:   50,
    			Age2:   101,
    			Mac1Score1: "4C-CC-6A-D6-B1-1A"9.8,
    			Mac2Score2: "Z0-CC-6A-D6-B1-1A"-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 Mac2Score2 value `Z0-CC-6A-D6-B1-1A` is not a valid MAC address
    }

url

  • `-0.5` must be between 0 and 10
    }


min

  • 格式: min:min
  • 说明:参数大小最小为min(支持整形和浮点类型参数)。

  • 格式: url
  • 说明:URL
  • 示例:支持以http,https,ftp,file开头的地址。

    Code Block
    languagego
    func Example_Rule_UrlMin() {
    	type BizReq struct {
    		URL1 stringAge1   int     `v:"min:100"`
    		Age2   int     `v:"urlmin:100"`
    		URL2Score1 stringfloat32 `v:"urlmin:10.0"`
    		URL3Score2 stringfloat32 `v:"urlmin:10.0"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			URL1Age1: "http://goframe.org"  50,
    			Age2:   101,
    			URL2Score1: "ftp://goframe.org"9.8,
    			URL3Score2: "ws://goframe.org"10.1,
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The URL3Age1 value `ws://goframe.org` is not a valid URL address
    }

domain

  •  `50` must be equal or greater than 100
    	// The Score1 value `9.8` must be equal or greater than 10
    }


max

  • 格式: max:max
  • 说明:参数大小最大为max(支持整形和浮点类型参数)。

  • 格式: domain
  • 说明:域名
  • 示例:域名规则。xxx.yyy(首位必须为字母)。

    Code Block
    languagego
    func Example_Rule_DomainMax() {
    	type BizReq struct {
    		Domain1 stringAge1   int     `v:"max:"domain100"`
    		Domain2 stringAge2   int     `v:"domainmax:100"`
    		Domain3Score1 stringfloat32 `v:"domainmax:10.0"`
    		Domain4Score2 stringfloat32 `v:"domainmax:10.0"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Domain1Age1: "goframe.org"   99,
    			Domain2Age2: "a.b"   101,
    			Domain3Score1: "goframe#org"9.9,
    			Domain4Score2: "1a10.2b"1,
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The Domain3Age2 value `101` `goframe#org`must isbe notequal aor validlesser domainthan format100
    	// The Domain4Score2 value `1a`10.2b`1` must isbe notequal aor validlesser domainthan format10
    }

size


json

  • 格式: json
  • 说明:判断数据格式为JSON

  • 格式: size:size
  • 说明:参数长度 size (长度参数为整形),注意底层使用Unicode计算长度,因此中文一个汉字占1个长度单位。

    Code Block
    languagego
    func Example_Rule_SizeJson() {
    	type BizReq struct {
    		Size1JSON1 string `v:"size:10json"`
    		Size2JSON2 string `v:"size:5json"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Size1JSON1: "goframe欢迎你"{\"name\":\"goframe\",\"author\":\"郭强\"}",
    			Size2JSON2: "{\"name\":\"goframe\",\"author\":\"郭强\",\"test\"}",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(err)
    	}
    
    	// Output:
    	// The Size2JSON2 value `goframe` length must be 5
    }

length

  • `{"name":"goframe","author":"郭强","test"}` is not a valid JSON string
    }


integer

  • 格式: integer
  • 说明:整数(正整数或者负整数)。

  • 格式: length:min,max
  • 说明:参数长度minmax(长度参数为整形),注意底层使用Unicode计算长度,因此中文一个汉字占1个长度单位。

    Code Block
    languagego
    func Example_Rule_LengthInteger() {
    	type BizReq struct {
    		Length1Integer string `v:"length:5,10"integer"`
    		Float   string `v:"integer"`
    		Length2Str     string `v:"length:10,15integer"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Length1: "goframe欢迎你Integer: "100",
    			Float:   "10.0",
    			Length2Str:     "goframe",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.Join(err.Strings()
    	}
    
    	// Output:, "\n"))
    	}
    
    	// Output:
    	// The Float value `10.0` is not an integer
    	// The Length2Str value `goframe` lengthis mustnot be between 10 and 15an integer
    }
min-length

float

  • 格式: min-length:min float
  • 说明:浮点数。说明:参数长度最小为min(长度参数为整形),注意底层使用Unicode计算长度,因此中文一个汉字占1个长度单位。

    Code Block
    languagego
    func Example_Rule_MinLengthFloat() {
    	type BizReq struct {
    		MinLength1Integer string `v:"min-length:10"float"`
    		Float   string `v:"float"`
    		MinLength2Str     string `v:"min-length:8float"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			MinLength1Integer: "100",
    			Float:   "goframe欢迎你10.0",
    			MinLength2Str:     "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

  •  Str value `goframe` is invalid
    }


boolean

  • 格式: boolean
  • 说明:布尔值(1,true,on,yestrue | 0,false,off,no,""false)。

  • 格式: max-length:max
  • 说明:参数长度最大为max(长度参数为整形),注意底层使用Unicode计算长度,因此中文一个汉字占1个长度单位。

    Code Block
    languagego
    func Example_Rule_MaxLengthBoolean() {
    	type BizReq struct {
    		MaxLength1 string{
    		Boolean bool    `v:"boolean"`
    		Integer int     `v:"boolean"`
    		Float   float32 `v:"boolean"`
    		Str1    string  `v:"boolean"`
    		Str2    string  `v:"max-length:10boolean"`
    		MaxLength2Str3    string  `v:"max-length:5boolean"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Boolean: true,
    			Integer: 1,
    			MaxLength1: "goframe欢迎你Float:   10.0,
    			Str1:    "on",
    			Str2:    "",
    			MaxLength2Str3:    "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 MaxLength2Str3 value `goframe` lengthfield must be equaltrue or lesser than 5false
    }
between

same

  • 格式: between:min,max same:field
  • 说明:参数值必需与field字段参数的值相同。
  • 示例:在用户注册时,提交密码Password和确认密码Password2必须相等(服务端校验)。说明:参数大小minmax(支持整形和浮点类型参数)。

    Code Block
    languagego
    func Example_Rule_BetweenSame() {
    	type BizReq struct {
    		Age1 Name  int    string `v:"between:1,100required"`
    		Age2Password   int     string `v:"between:1,100required|same:Password2"`
    		Score1Password2 float32string `v:"between:0.0,10.0required"`
    		Score2 float32 `v:"between:0.0,10.0"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Age1Name:   50,
    			Age2:   101"gf",
    			Score1Password:  9"goframe.8org",
    			Score2Password2: -0.5"goframe.net",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.PrintPrintln(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The Age2Password value `101``goframe.org` must be betweenthe 1same and 100
    	// The Score2 value `-0.5` must be between 0 and 10as field Password2
    }
min

different

  • 格式: min:min different:field
  • 说明:参数值不能与field字段参数的值相同。
  • 示例:备用邮箱OtherMailAddr和邮箱地址MailAddr必须不相同。说明:参数大小最小为min(支持整形和浮点类型参数)。

    Code Block
    languagego
    func Example_Rule_MinDifferent() {
    	type BizReq struct {
    		Age1Name        int    string `v:"min:100required"`
    		Age2 MailAddr  int     `v:"min:100"`
    		Score1 float32 string `v:"min:10.0required"`
    		Score2ConfirmMailAddr float32string `v:"min:10.0required|different:MailAddr"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Age1:Name:            50"gf",
    			Age2MailAddr:       101,
    			Score1: 9.8 "gf@goframe.org",
    			Score2ConfirmMailAddr: 10"gf@goframe.1org",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.JoinPrintln(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The Age1ConfirmMailAddr value `50` must be equal or greater than 100
    	// The Score1 value `9.8``gf@goframe.org` must be equaldifferent orfrom greaterfield than 10MailAddr
    }
max

eq

  • 格式: maxeq:maxfield
  • 说明:参数值必需与field字段参数的值相同。same规则的别名,功能同same规则。说明:参数大小最大为max(支持整形和浮点类型参数)。

    Code Block
    languagego
    func Example_Rule_MaxEQ() {
    	type BizReq struct {
    		Age1Name   int   string  `v:"max:100required"`
    		Age2Password   int    string `v:"maxrequired|eq:100Password2"`
    		Score1Password2 float32string `v:"max:10.0required"`
    		Score2 float32 `v:"max:10.0"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Age1Name:   99,
    			Age2:   101"gf",
    			Score1Password: 9.9 "goframe.org",
    			Score2Password2: 10"goframe.1net",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.JoinPrintln(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The Age2Password value `101``goframe.org` must be equal orto lesserfield than 100
    	// The Score2 Password2 value `10.1` must be equal or lesser than 10`goframe.net`
    }
json

not-eq

  • 格式: json not-eq:field
  • 说明:参数值必需与field字段参数的值不相同。different规则的别名,功能同different规则。说明:判断数据格式为JSON

    Code Block
    languagego
    func Example_Rule_JsonNotEQ() {
    	type BizReq struct {
    		JSON1Name          string `v:"required"`
    		MailAddr      string `v:"jsonrequired"`
    		JSON2OtherMailAddr string `v:"jsonrequired|not-eq:MailAddr"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{ BizReq{
    			Name:          "gf",
    			JSON1MailAddr: "{\"name\":\"goframe\",\"author\":\"郭强\"}      "gf@goframe.org",
    			JSON2OtherMailAddr: "{\"name\":\"goframe\",\"author\":\"郭强\",\"test\"}",gf@goframe.org",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.PrintPrintln(err)
    	}
    
    	// Output:
    	// The JSON2OtherMailAddr value `{"name":"goframe","author":"郭强","test"}` is not a valid JSON string
    }

integer

  • `gf@goframe.org` must not be equal to field MailAddr value `gf@goframe.org`
    }


gt

  • 格式: gt:field
  • 说明:参数值必需大于给定字段对应的值。

  • 格式: integer
  • 说明:整数(正整数或者负整数)。

    Code Block
    languagego
    func Example_Rule_IntegerGT() {
    	type BizReq struct {
    		Integer string `v:"integer"`Value1 int
    		FloatValue2  int string `v:"integergt:Value1"`
    		Str     stringValue3 int `v:"integergt:Value1"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			IntegerValue1: "100"1,
    			FloatValue2:   "10.0"1,
    			StrValue3:     "goframe"2,
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.JoinPrintln(err.StringsString(), "\n"))
    	}
    
    	// Output:
    	// The FloatValue2 value `10.0``1` ismust notbe an integer
    	// The Str value `goframe` is not an integergreater than field Value1 value `1`
    }
float

gte

  • 格式: gte: floatfield
  • 说明:浮点数。说明:参数值必需大于或等于给定字段对应的值。

    Code Block
    languagego
    func Example_Rule_FloatGTE() {
    	type BizReq struct {
    		Integer string `v:"float"`Value1 int
    		FloatValue2   stringint `v:"floatgte:Value1"`
    		Str     stringValue3 int `v:"floatgte:Value1"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			IntegerValue1: "100"2,
    			FloatValue2:   "10.0"1,
    			StrValue3:     "goframe"2,
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.PrintPrintln(err.String())
    	}
    
    	// Output:
    	// The StrValue2 value `goframe` is invalid `1` must be greater than or equal to field Value1 value `2`
    }
boolean

lt

  • 格式: boolean lt:field
  • 说明:参数值必需小于给定字段对应的值。说明:布尔值(1,true,on,yestrue | 0,false,off,no,""false)。

    Code Block
    languagego
    func Example_Rule_BooleanLT() {
    	type BizReq struct {
    		Boolean bool    `v:"boolean"`Value1 int
    		IntegerValue2 int     `v:"boolean"`
    		Float   float32 `v:"boolean"lt:Value1"`
    		Str1Value3   int string  `v:"boolean"`
    		Str2    string  `v:"booleanlt:Value1"`
    		Str3    string  `v:"boolean"`
    	}
    
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			Boolean: true,
    			Integer: 1,
    			Float:   10.0, context.Background()
    		req = BizReq{
    			Str1Value1:    "on"2,
    			Str2Value2:    ""1,
    			Str3Value3:    "goframe"2,
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.JoinPrintln(err.StringsString(), "\n"))
    	}
    
    	// Output:
    	// The FloatValue3 value `10` field`2` must be truelesser or false
    	// The Str3 value `goframe` field must be true or falsethan field Value1 value `2`
    }
same

lte

  • 格式: samelte:field
  • 说明:参数值必需与field字段参数的值相同。
  • 示例:在用户注册时,提交密码Password和确认密码Password2必须相等(服务端校验)。说明:参数值必需小于或等于给定字段对应的值。

    Code Block
    languagego
    func Example_Rule_SameLTE() {
    	type BizReq struct {
    		Name      string `v:"required"` {
    		PasswordValue1 int
    		Value2 stringint `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).Run(ctx); err != nil {
    		fmt.Println(err.String())
    	}
    
    	// Output:
    	// The PasswordValue3 value `goframe.org``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
    languagego
    func Example_Rule_DifferentIn() {
    	type BizReq struct {
    		NameID          uint  string `v:"required" dc:"Your Id"`
    		MailAddr  Name      string `v:"required" dc:"Your name"`
    		ConfirmMailAddrGender uint  string `v:"required|different:MailAddrin:0,1,2" dc:"0:Secret;1:Male;2:Female"`
    	}
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			NameID:            "gf"1,
    			MailAddrName:        "gf@goframe.orgtest",
    			ConfirmMailAddrGender: "gf@goframe.org"3,
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Println(err)
    	}
    
    	// Output:
    	// The ConfirmMailAddrGender value `gf@goframe.org``3` mustis benot differentin fromacceptable field MailAddrrange: 0,1,2
    }


not-in

  • 格式: not-in:value1,value2,...
  • 说明:参数值应该在说明:参数值不应该在value1,value2,...中(字符串匹配)。
  • 示例:性别字段Gender的值必须在示例:无效索引InvalidIndex的值必须不在-1/0/1/2中。

    Code Block
    languagego
    func Example_Rule_InNotIn() {
    	type BizReq struct {
    		ID           uint   `v:"required" dc:"Your Id"`
    		Name         string `v:"required" dc:"Your name"`
    		GenderInvalidIndex uint   `v:"not-in:0,-1,2" dc:"0:Secret;1:Male;2:Female0,1"`
    	}
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			ID:           1,
    			Name:         "test",
    			GenderInvalidIndex: 31,
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.Println(err)
    	}
    
    	// Output:
    	// The GenderInvalidIndex value `3``1` ismust not be in acceptable range: -1,0,1,2
    }
not-in

regex

  • 格式: not-in:value1,value2,...
  • 说明:参数值不应该在value1,value2,...中(字符串匹配)。
  • regex:pattern
  • 说明:参数值应当满足正则匹配规则pattern

    示例:无效索引InvalidIndex的值必须不在-1/0/1中。

    Code Block
    languagego
    func Example_Rule_NotInRegex() {
    	type BizReq struct {
    		ID           uint   Regex1 string `v:"required" dc:"Your Idregex:[1-9][0-9]{4,14}"`
    		Name         Regex2 string `v:"required" dc:"Your nameregex:[1-9][0-9]{4,14}"`
    		InvalidIndexRegex3 uintstring   `v:"not-inregex:-1,0,1[1-9][0-9]{4,14}"`
    	}
    	var (
    		ctx = context.Background()
    		req = BizReq{
    			IDRegex1:           1"1234",
    			Name:        	Regex2: "test01234",
    			InvalidIndexRegex3: 1"10000",
    		}
    	)
    	if err := g.Validator().Data(req).Run(ctx); err != nil {
    		fmt.PrintlnPrint(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The InvalidIndexRegex1 value `1``1234` must not be in regex of: [1-9][0-9]{4,14}
    	// The Regex2 value `01234` must be in regex rangeof: -1,0,1[1-9][0-9]{4,14}
    }


not-regex

  • 格式: not-regex:pattern
  • 说明:参数值应当满足正则匹配规则说明:参数值不应当满足正则匹配规则pattern

    Code Block
    languagego
    func Example_Rule_RegexNotRegex() {
    	type BizReq struct {
    		Regex1 string `v:"regex:[1-9][0-9]{4,14}"` BizReq struct {
    		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().Data(req).Run(ctx); err != nil {
    		fmt.Print(gstr.Join(err.Strings(), "\n"))
    	}
    
    	// Output:
    	// The Regex1Regex2 value `1234` must be in regex of: [1-9][0-9]{4,14}
    	// The Regex2 value `01234` must should not be in regex of: [1-9][0-9]\d{4,14}
    }






Panel
titleContent Menu

Table of Contents