go --- validator validator practice

Project address: https://github.com/go-playground/validator

Other Chinese documentation: https://www.cnblogs.com/zj420255586/p/13542395.html
 

1. Operator description

, multi-operator split
| or
- skip verification

 

2. Description of commonly used marks

mark illustrate For example
required required validate:“required”
omitempty space time ignore ???
len length
eq equal
gt more than the
gte greater or equal to
lt less than
lte less than or equal to
min minimum value
max maximum value
isdefault Defaults ???
oneof one of them
email String value contains a valid email
json Whether the string value is valid JSON
url Whether the string value contains a valid url
uri Whether the string value contains a valid uri
base64 Whether the string value contains a valid base64 value
contains String value contains substring value
ip Whether the string value contains a valid IP address
ipv4 Whether the string value contains a valid ipv4 address
datetime whether the string value contains a valid date
gtfield greater than the same struct field

 

3. Precautions

  1. When the search condition conflicts with a special mark, such as: comma (,), or operation (|), dash (-), etc., you need to use UTF-8 hexadecimal representation

    example:

    Copytype Test struct {
          
          
       Field1 string  `validate:"excludesall=|"`    // 错误
       Field2 string `validate:"excludesall=0x7C"` // 正确.
    }
    
  2. The error object can be obtained through validationErrors := errs.(validator.ValidationErrors) to customize the return response error

  3. Translation of custom verification results

    Copy// 初始化翻译器
    func validateInit() {
          
          
    	zh_ch := zh.New()
    	uni := ut.New(zh_ch)               // 万能翻译器,保存所有的语言环境和翻译数据
    	Trans, _ = uni.GetTranslator("zh") // 翻译器
    	Validate = validator.New()
    	_ = zh_translations.RegisterDefaultTranslations(Validate, Trans)
    	// 添加额外翻译
    	_ = Validate.RegisterTranslation("required_without", Trans, func(ut ut.Translator) error {
          
          
    		return ut.Add("required_without", "{0} 为必填字段!", true)
    	}, func(ut ut.Translator, fe validator.FieldError) string {
          
          
    		t, _ := ut.T("required_without", fe.Field())
    		return t
    	})
    }
    

 

4. Code practice

package main

import (
	"fmt"
	"github.com/go-playground/validator"
)

var validate = validator.New()

func main() {
    
    
	type Inner struct {
    
    
		ContainsString string `validate:"contains=111"`
	}
	inner := &Inner{
    
    ContainsString: "11@"}
	err := validate.Struct(inner)
	if err != nil {
    
    
		fmt.Println(err.Error())
	}

	//required 必填验证
	type RequiredTest struct {
    
    
		Name string
		Age  int `validate:"required"`
	}
	//requiredTest := &RequiredTest{Name:"11111",Age:10}
	requiredTest := &RequiredTest{
    
    Name: "11111"}
	err = validate.Struct(requiredTest)
	if err != nil {
    
    
		fmt.Println(err.Error())
	}

	//len 长度限制
	type LenTest struct {
    
    
		Name string `validate:"len=3"`
		Age  int
	}
	//lenTest := &LenTest{Name:"111"}
	lenTest := &LenTest{
    
    Name: "1111"}
	err = validate.Struct(lenTest)
	if err != nil {
    
    
		fmt.Println(err.Error())
	}

	// eq 等于
	type EqTest struct {
    
    
		Name string
		Age  int `validate:"eq=3"`
	}
	//eqTest := &EqTest{Age:3}
	eqTest := &EqTest{
    
    Age: 10}
	err = validate.Struct(eqTest)
	if err != nil {
    
    
		fmt.Println(err.Error())
	}

	// gt 大于
	type GtTest struct {
    
    
		Name string
		Age  int `validate:"gt=3"`
	}
	//gtTest := &GtTest{Age:10}
	gtTest := &GtTest{
    
    Age: 3}
	err = validate.Struct(gtTest)
	if err != nil {
    
    
		fmt.Println(err.Error())
	}

	// gte 等于
	type GteTest struct {
    
    
		Name string
		Age  int `validate:"gte=3"`
	}
	gteTest := &GteTest{
    
    Age: 2}
	//gteTest := &GteTest{Age:3}
	err = validate.Struct(gteTest)
	if err != nil {
    
    
		fmt.Println(err.Error())
	}

	//lt 小于
	type LtTest struct {
    
    
		Name string
		Age  int `validate:"lt=5"`
	}
	//ltTest := &LtTest{Age:2}
	ltTest := &LtTest{
    
    Age: 8}
	err = validate.Struct(ltTest)
	if err != nil {
    
    
		fmt.Println(err.Error())
	}

	//lte 小于等于
	type LteTest struct {
    
    
		Name string
		Age  int `validate:"lte=5"`
	}
	lteTest := &LteTest{
    
    Age: 2}
	//lteTest := &LteTest{Age:8}
	err = validate.Struct(lteTest)
	if err != nil {
    
    
		fmt.Println(err.Error())
	}

	//eqfield 同一结构体字段相等
	type EqfieldTest struct {
    
    
		Name  string
		Age   int `validate:"eqfield=Count"`
		Count int
	}
	//eqfieldTest := &EqfieldTest{Age:2,Count:2}
	eqfieldTest := &EqfieldTest{
    
    Age: 2, Count: 10}
	err = validate.Struct(eqfieldTest)
	if err != nil {
    
    
		fmt.Println(err.Error())
	}

	//min 最小值
	type MinTest struct {
    
    
		Name  string
		Age   int `validate:"min=18"`
		Count int
	}
	minTest := &MinTest{
    
    Age:12,Count:2}
	//minTest := &MinTest{Age: 18, Count: 10}
	err = validate.Struct(minTest)
	if err != nil {
    
    
		fmt.Println(err.Error())
	}

	//max 最大值
	type MaxTest struct {
    
    
		Name  string
		Age   int `validate:"max=18"`
	}
	//maxTest := &MaxTest{Age:12}
	maxTest := &MaxTest{
    
    Age: 20}
	err = validate.Struct(maxTest)
	if err != nil {
    
    
		fmt.Println(err.Error())
	}


	//oneof 其中之一
	type OneofTest struct {
    
    
		Name  string
		Age   int `validate:"oneof=10 15"`
	}
	oneofTest := &OneofTest{
    
    Age:12}
	//oneofTest := &OneofTest{Age:10}
	err = validate.Struct(oneofTest)
	if err != nil {
    
    
		fmt.Println(err.Error())
	}


	//email 是否包含电子邮件
	type EmailTest struct {
    
    
		Email  string `validate:"email"`
		Age   int
	}
	//emailTest := &EmailTest{Email:"123qq.com"}  //不通过
	//emailTest := &EmailTest{Email:"123@com"}  //不通过
	//emailTest := &EmailTest{Email:"[email protected]"}  //通过
	//emailTest := &EmailTest{Email:"[email protected]"}  //通过
	emailTest := &EmailTest{
    
    Email:"@q.com"}  //不通过
	//emailTest := &EmailTest{Email:"帅@q.com"}  //通过
	err = validate.Struct(emailTest)
	if err != nil {
    
    
		fmt.Println(err.Error())
	}

}

 
If there is anything wrong, please point it out, thank you~

Guess you like

Origin blog.csdn.net/my_miuye/article/details/124763238