Versions Compared

Key

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

单数据校验 -  CheckValue

接口文档:https://pkg.go.dev/github.com/gogf/gf/v2/util/gvalid

Code Block
languagego
func CheckValue(ctx context.Context, value interface{}, rules string, messages interface{}, params ...interface{}) Error

单数据校验比较简单,我们来看几个示例。

校验数据长度,使用默认的错误提示

Code Block
languagego
package main

import (
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
)

func main() {
	var (
		ctx  = gctx.New()
		rule = "length:6,16"
	)

	if err := g.Validator().Rules(rule).CheckValue(ctx, "123456"); err != nil {
		fmt.Println(err.String())
	}
	if err := g.Validator().Rules(rule).CheckValue(ctx, "12345"); err != nil {
		fmt.Println(err.String())
	}
}

执行后,终端输出:

Code Block
languagexml
The value length must be between 6 and 16

校验数据类型及大小,并且使用自定义的错误提示

Code Block
languagego
package main

import (
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
)

func main() {
	var (
		ctx      = gctx.New()
		rule     = "integer|between:6,16"
		messages = "请输入一个整数|参数大小不对啊老铁"
		value    = 5.66
	)
	if err := g.Validator().Rules(rule).Messages(messages).CheckValue(ctx, value); err != nil {
		fmt.Println(err.Map())
	}
}

执行后,终端输出:

Code Block
languagexml
map[between:参数大小不对啊老铁 integer:请输入一个整数]

可以看到,多个规则以及多个自定义错误提示之间使用英文 | 号进行分割,注意自定义错误提示的顺序和多规则的顺序一一对应。messages参数除了支持string类型以外,还支持map[string]string类型,请看以下例子:

Code Block
languagego
package main

import (
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
)

func main() {
	var (
		ctx      = gctx.New()
		rule     = "url|min-length:11"
		value    = "goframe.org"
		messages = map[string]string{
			"url":        "请输入正确的URL地址",
			"min-length": "地址长度至少为:min位{min}位",
		}
	)
	if err := g.Validator().Rules(rule).Messages(messages).CheckValue(ctx, value); err != nil {
		fmt.Println(err.Map())
	}
}

执行后,终端输出:

Code Block
languagexml
map[url:请输入正确的URL地址]

使用自定义正则校验数据格式,使用默认错误提示

Code Block
languagego
package main

import (
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
)

func main() {
	var (
		ctx  = gctx.New()
		rule = `regex:\d{6,}|\D{6,}|max-length:16`
	)
	if err := g.Validator().Rules(rule).CheckValue(ctx, `123456`); err != nil {
		fmt.Println(err)
	}
	if err := g.Validator().Rules(rule).CheckValue(ctx, `abcde6`); err != nil {
		fmt.Println(err)
	}
}

执行后,终端输出:

Code Block
languagexml
The value `abcde6` must be in regex of: \d{6,}|\D{6,}











Panel
titleContent Menu

Table of Contents