beego的validation表单验证库的使用

下载beego/validation

go get github.com/astaxie/beego/validation

直接用途

package main

import (
	"fmt"
	"github.com/astaxie/beego/validation"
)

type User struct {
	Name string
	Age int
}
func main() {
	//// 修改默认的错误提示信息
	validation.SetDefaultMessage(map[string]string{
		"Required": "必填字段,不能为空",
		"Max": "允许的最大年龄是 %d",
		"Range": "允许的年龄范围是:%d-%d",
	})

	u := User{Age: 141}
	valid := validation.Validation{}
	valid.Required(u.Name, "name:姓名")
	valid.Max(u.Age, 140, "age:年龄")
	valid.Range(u.Age, 0, 140, "age")

	// 1. 获取一个验证的错误结果
	/*
	ret1 := valid.Max(u.Age, 140, "age:年龄")
	if !ret1.Ok {
		fmt.Println(ret1.Error.Key, ret1.Error.Message)
	}
	 */

	// 2. 获取所有验证的错误结果
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			fmt.Println(err.Key, err.Message)
		}
	}
}

结构体标签使用

package main

import (
	"fmt"
	"github.com/astaxie/beego/validation"
	"regexp"
	"strings"
)

type user struct {
	Name string `valid:"Required;Match(/^(test)?\\w*@;com$/)"`
	Age int `valid:"Required;Range(0,140)"`
}
func main() {
	//// 修改默认的错误提示信息
	validation.SetDefaultMessage(map[string]string{
		"Required": "必填字段:不能为空",
		"Max":      "允许的最大年龄是:%d",
		"Range":    "允许的年龄范围是:%d-%d",
		"Match": 	"正则表达式不匹配:请检查 %s",
	})
	valid := validation.Validation{}
	u := user{Name: "testMaya@;com1", Age: 180}
	b, err := valid.Valid(&u)
	if b {
		fmt.Println("验证成功")
	}else{
		fmt.Printf("验证失败:%v\n", err)
	}
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			// 正则表达式不想对外暴露,所以切割去掉了
			if ok, _ := regexp.MatchString("^.*\\.Match$", err.Key); ok {
				fmt.Println(err.Key, strings.Split(err.Message, ":")[0])
			}else {
				fmt.Println(err.Key, err.Message)
			}
		}
	}
}

自定义添加函数

package main

import (
	"fmt"
	"github.com/astaxie/beego/validation"
	"strings"
)

func IsMe(v *validation.Validation, obj interface{}, key string) {
	name, ok := obj.(string)
	if !ok {
		_ = v.SetError(strings.Split(key, ".")[0], "必须是字符串类型")
		return
	}
	if name != "me" {
		_ = v.SetError(key, "is not me!")
	}
}
type user struct {
	Name string `valid:"Required;IsMe"`
	Age int `valid:"Required;Range(0,140);IsMe"`
}
func main() {
	//// 修改默认的错误提示信息
	validation.SetDefaultMessage(map[string]string{
		"Required": "必填字段:不能为空",
		"Max":      "允许的最大年龄是:%d",
		"Range":    "允许的年龄范围是:%d-%d",
		"Match": 	"正则表达式不匹配:请检查 %s",
	})
	err := validation.AddCustomFunc("IsMe", IsMe)
	if err != nil {
		fmt.Println(err)
	}
	valid := validation.Validation{}
	u := user{"me", 18}
	b, err := valid.Valid(&u)
	if !b {
		fmt.Println("验证失败", err)
	}
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			fmt.Println(err.Key, err.Message)
		}
	}
}

结构体标签内置函数

Required
Min(min int)
Max(max int)
Range(min, max int)
MinSize(min int)
MaxSize(max int)
Length(length int)
Alpha
Numeric
AlphaNumeric
Match(pattern string)
AlphaDash
Email
IP
Base64
Mobile
Tel
Phone
ZipCode

综合案例,包括手机号长度和手机号是否有效验证

package main

import (
	"fmt"
	"github.com/astaxie/beego/validation"
	"strings"
)

func IsMe(v *validation.Validation, obj interface{}, key string) {
	name, ok := obj.(string)
	if !ok {
		_ = v.SetError(strings.Split(key, ".")[0], "必须是字符串类型")
		return
	}
	if name != "me" {
		_ = v.SetError(key, "is not me!")
	}
}
type user struct {
	Name string `valid:"Required;IsMe"`
	Age int `valid:"Required;Range(0,140)"`
	Phone string `valid:"Required;Length(11);Mobile"`
}
func main() {
	//// 修改默认的错误提示信息
	validation.SetDefaultMessage(map[string]string{
		"Required": "必填字段:不能为空",
		"Max":      "允许的最大年龄是:%d",
		"Range":    "允许的年龄范围是:%d-%d",
		"Match": 	"正则表达式不匹配:请检查 %s",
		"Length":	"长度必须是:%d位",
	})
	err := validation.AddCustomFunc("IsMe", IsMe)
	if err != nil {
		fmt.Println(err)
	}
	valid := validation.Validation{}
	u := user{"me", 18, "29566556655"}
	b, err := valid.Valid(&u)
	if !b {
		fmt.Println("验证失败", err)
	}
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			fmt.Println(err.Message)
		}
	}
}
posted @ 2022-09-07 11:18  专职  阅读(982)  评论(0编辑  收藏  举报