Skip to content

Commit

Permalink
checker: add list
Browse files Browse the repository at this point in the history
  • Loading branch information
wuhan005 committed Feb 21, 2024
1 parent 9dd5e5a commit 95c67f3
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
16 changes: 15 additions & 1 deletion checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -45,6 +46,7 @@ var Checkers = map[string]CheckFunc{
"phone": phone,
"idcard": idCard,
"equal": equal,
"list": list,
}

func required(c CheckerContext) *ErrContext {
Expand Down Expand Up @@ -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
}
21 changes: 21 additions & 0 deletions checker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:"用户名"`
Expand Down
2 changes: 2 additions & 0 deletions template.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ var errorTemplateChinese = map[string]string{
"phone": "不是合法的号码",
"idcard": "不是合法的身份证号",
"equal": "的值前后不相同",
"list": "不是一个有效的值",

"_checkerNotFound": "检查规则未找到}}",
"_unknownErrorTemplate": "{{未知错误}}",
Expand All @@ -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}}",
Expand Down

0 comments on commit 95c67f3

Please sign in to comment.