gvalid新增对运行时对象属性的校验支持

This commit is contained in:
John
2018-04-10 12:01:17 +08:00
parent 24b8c2459e
commit 067c07903c
3 changed files with 46 additions and 5 deletions

View File

@ -18,6 +18,8 @@ import (
"gitee.com/johng/gf/g/util/gregx"
"gitee.com/johng/gf/g/encoding/gjson"
"gitee.com/johng/gf/g/container/gmap"
"github.com/fatih/structs"
"gitee.com/johng/gf/g/util/gconv"
)
/*
@ -401,6 +403,15 @@ func CheckMap(params map[string]string, rules map[string]string, msgs...map[stri
return nil
}
// 校验struct对象属性object参数也可以是一个指向对象的指针返回值同CheckMap方法
func CheckObject(object interface{}, rules map[string]string, msgs...map[string]interface{}) map[string]map[string]string {
params := make(map[string]string)
for k, v := range structs.Map(object) {
params[k] = gconv.String(v)
}
return CheckMap(params, rules, msgs...)
}
// 检测单条数据的规则其中params参数为非必须参数可以传递所有的校验参数进来进行多参数对比(部分校验规则需要)
// msgs为自定义错误信息由于同一条数据的校验规则可能存在多条为方便调用参数类型支持string/map[string]string允许传递多个自定义的错误信息如果类型为string那么中间使用"|"符号分隔多个自定义错误
// values参数为表单联合校验参数对于需要联合校验的规则有效required-*、same、different

View File

@ -64,6 +64,28 @@ func Test_CheckMap(t *testing.T) {
}
}
func Test_CheckObject(t *testing.T) {
type Object struct {
Name string
Age int
}
rules := map[string]string {
"Name" : "required|length:6,16",
"Age" : "between:18,30",
}
msgs := map[string]interface{} {
"Name" : map[string]string {
"required" : "名称不能为空",
"length" : "名称长度为:min到:max个字符",
},
"Age" : "年龄为18到30周岁",
}
obj := &Object{"john", 16}
if m := gvalid.CheckObject(obj, rules, msgs); m == nil {
t.Error("CheckObject校验失败")
}
}
func Test_Required(t *testing.T) {
if m := gvalid.Check("1", "required", nil); m != nil {
t.Error(m)

View File

@ -2,17 +2,25 @@ package main
import (
"fmt"
"reflect"
"github.com/fatih/structs"
)
type T struct {
Name string
Age int
S struct {
N string
}
}
func (t *T) Test2Test() {}
func main() {
obj := &T{}
v := reflect.ValueOf(obj).MethodByName("Test2Test")
fmt.Println(v.IsValid())
v := &T{
Name : "john",
Age : 18,
}
v.S.N = "ttt"
fmt.Println(structs.Map(v))
}