diff --git a/checker.go b/checker.go index 4f48b77..ea9ecbd 100644 --- a/checker.go +++ b/checker.go @@ -2,12 +2,13 @@ package govalid import ( "fmt" - "golang.org/x/text/language" "reflect" "regexp" "strconv" "strings" "unicode/utf8" + + "golang.org/x/text/language" ) // CheckFunc is the type of checker function. @@ -45,6 +46,7 @@ var Checkers = map[string]CheckFunc{ "phone": phone, "idcard": idCard, "equal": equal, + "list": list, } func required(c CheckerContext) *ErrContext { @@ -384,3 +386,15 @@ func equal(c CheckerContext) *ErrContext { } return MakeFieldNotFoundError(c) } + +func list(c CheckerContext) *ErrContext { + ctx := NewErrorContext(c) + value := fmt.Sprintf("%v", ctx.FieldValue) + allowValues := strings.Split(c.Rule.params[0], ",") + for _, v := range allowValues { + if value == v { + return nil + } + } + return ctx +} diff --git a/checker_test.go b/checker_test.go index 3fd337e..186af5f 100644 --- a/checker_test.go +++ b/checker_test.go @@ -668,6 +668,27 @@ func Test_Equal(t *testing.T) { assert.Nil(t, errs) } +func Test_List(t *testing.T) { + v := struct { + Role string `valid:"list:admin,editor,viewer" label:"角色"` + }{ + Role: "superadmin", + } + errs, ok := Check(v) + assert.False(t, ok) + assert.Equal(t, 1, len(errs)) + assert.Equal(t, "角色不是一个有效的值", errs[0].Error()) + + v = struct { + Role string `valid:"list:admin,editor,viewer" label:"角色"` + }{ + Role: "admin", + } + errs, ok = Check(v) + assert.True(t, ok) + assert.Nil(t, errs) +} + func Test_StructSlice(t *testing.T) { type user struct { Name string `valid:"required" label:"用户名"` diff --git a/template.go b/template.go index f9e2f61..2285587 100644 --- a/template.go +++ b/template.go @@ -18,6 +18,7 @@ var errorTemplateChinese = map[string]string{ "phone": "不是合法的号码", "idcard": "不是合法的身份证号", "equal": "的值前后不相同", + "list": "不是一个有效的值", "_checkerNotFound": "检查规则未找到}}", "_unknownErrorTemplate": "{{未知错误}}", @@ -44,6 +45,7 @@ var errorTemplateEnglish = map[string]string{ "phone": " is not a valid phone number", "idcard": " is not a valid ID card number", "equal": " the value before and after is not the same", + "list": " is not a valid value", "_checkerNotFound": " check rule not found}}", "_unknownErrorTemplate": "{{unknown error}}",