codecamp

GoFrame Map校验-基本使用

默认错误提示

package main

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

func main() {
	var (
		ctx    = gctx.New()
		params = map[string]interface{}{
			"passport":  "",
			"password":  "123456",
			"password2": "1234567",
		}
		rules = map[string]string{
			"passport":  "required|length:6,16",
			"password":  "required|length:6,16|same:password2",
			"password2": "required|length:6,16",
		}
	)   
	err := g.Validator().Rules(rules).Data(params).Run(ctx)  
	if err != nil {
		g.Dump(err.Maps())
	}
}

执行后,终端输出:

{
    "passport": {
        "required": "The passport field is required",
        "length":   "The passport value `` length must be between 6 and 16",
    },
    "password": {
        "same": "The password value `123456` must be the same as field password2",
    },
}

自定义错误提示

package main

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

func main() {
	var (
		ctx    = gctx.New()
		params = map[string]interface{}{
			"passport":  "",
			"password":  "123456",
			"password2": "1234567",
		}
		rules = map[string]string{
			"passport":  "required|length:6,16",
			"password":  "required|length:6,16|same:password2",
			"password2": "required|length:6,16",
		}
		messages = map[string]interface{}{
			"passport": "账号不能为空|账号长度应当在{min}到{max}之间",
			"password": map[string]string{
				"required": "密码不能为空",
				"same":     "两次密码输入不相等",
			},
		}
	)  

	err := g.Validator().Messages(messages).Rules(rules).Data(params).Run(ctx)  
	if err != nil {
		g.Dump(err.Maps())
	}
}

该示例同时也展示了​messsages​自定义错误信息传递的两种数据类型,​string​或者​map[string]string​。其中​map[string]string​类型参数需要指定对应字段、对应规则的错误提示信息,是一个二维的“关联数组”。该示例执行后,终端输出:

{
    "passport": {
            "length": "账号长度应当在6到16之间",
            "required": "账号不能为空"
    },
    "password": {
            "same": "两次密码输入不相等"
    }
}


GoFrame Struct校验-Assoc关联
GoFrame Map校验-校验顺序性
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

GoFrame 核心组件

GoFrame 核心组件-数据库ORM

GoFrame 模块列表

GoFrame 模块列表-单元测试

GoFrame 模块列表-功能调试

GoFrame WEB服务开发

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }