圆月山庄资源网 Design By www.vgjia.com

目前大都是使用 validator

安装

go get gopkg.in/go-playground/validator.v9

原理

当然只能通过反射来实现了,之前写过一篇反射的文章 golang之反射和断言 ,里面有写到怎么通过反射获取struct tag。

读取struct tag之后就是对里面的标识符进行识别,然后进行验证了。具体可以去看源码。

demo

简单使用:

package main

import (
 "fmt"
 "gopkg.in/go-playground/validator.v9"
)

// User contains user information
type UserInfo struct {
 FirstName  string  `validate:"required"`
 LastName  string  `validate:"required"`
 Age   uint8  `validate:"gte=0,lte=100"`
 Email   string  `validate:"required,email"`
}


func main() {
 validate := validator.New()
 user := &UserInfo{
  FirstName:  "Badger",
  LastName:  "Smith",
  Age:   105,
  Email:   "",
 }
 err := validate.Struct(user)
 if err != nil {
  for _, err := range err.(validator.ValidationErrors) {
   fmt.Println(err)
  }
  return
 }
 fmt.Println("success")
}

输出:

Key: 'UserInfo.Age' Error:Field validation for 'Age' failed on the 'lte' tag
Key: 'UserInfo.Email' Error:Field validation for 'Email' failed on the 'required' tag

其它类型可以参照文档 https://godoc.org/gopkg.in/go-playground/validator.v9

几个例子:

1.IP
type UserInfo struct {
 Ip    string  `validate:"ip"`
}
2.数字
type UserInfo struct {
 Number float32 `validate:"numeric"`
}
3.最大值
type UserInfo struct {
 Number float32 `validate:"max=10"`
}
4.最小值
type UserInfo struct {
 Number float32 `validate:"min=10"`
}

自定义验证函数

package main

import (
 "fmt"
 "gopkg.in/go-playground/validator.v9"
 "unicode/utf8"
)

// User contains user information
type UserInfo struct {
 Name   string  `validate:"checkName"`
 Number float32 `validate:"numeric"`
}
// 自定义验证函数
func checkName(fl validator.FieldLevel) bool {
 count := utf8.RuneCountInString(fl.Field().String())
 fmt.Printf("length: %v \n", count)
 if count > 5 {
  return false
 }
 return true
}

func main() {
 validate := validator.New()
  //注册自定义函数,与struct tag关联起来
 err := validate.RegisterValidation("checkName", checkName)
 user := &UserInfo{
  Name:   "我是中国人,我爱自己的祖国",
  Number:   23,
 }
 err = validate.Struct(user)
 if err != nil {
  for _, err := range err.(validator.ValidationErrors) {
   fmt.Println(err)
  }
  return
 }
 fmt.Println("success")
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

标签:
golang,数据校验,golang校验,go,validator

圆月山庄资源网 Design By www.vgjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
圆月山庄资源网 Design By www.vgjia.com