Add not (!) to invert validation rules

This commit is contained in:
Nise Void 2020-04-24 12:36:13 +02:00
parent f79b7c6649
commit cb4720cd31
Signed by: NiseVoid
GPG Key ID: FBA14AC83EA602F3
2 changed files with 28 additions and 2 deletions

View File

@ -206,10 +206,15 @@ func getTagFuncs(i int, ft reflect.StructField, kind reflect.Kind, tags []string
continue
}
check, val := getTagFunc(tag, value, kind)
var not bool
if strings.HasPrefix(tag, `!`) {
not = true
}
check, val := getTagFunc(strings.TrimPrefix(tag, `!`), value, kind)
f := func(rv reflect.Value) ([]ValidationError, bool) {
if check(rv, val) {
if check(rv, val) == !not {
return nil, true
}

View File

@ -76,3 +76,24 @@ func TestValidationErrorField(t *testing.T) {
t.Fatal(`Expected errors to be A.B.C[0].D and A.B.C[2].D; got`, errs[0].Field, `and`, errs[1].Field)
}
}
func TestNot(t *testing.T) {
type s struct {
A string `validate:"!len=3"`
B int `validate:"!eq=3"`
}
var pass1 = s{`ab`, 2}
var pass2 = s{`abcd`, 4}
var fail = s{`abc`, 3}
check(t, pass1, 0)
check(t, pass2, 0)
check(t, fail, 2)
errs := Validate(fail)
if errs[0].Check != `!len` || errs[1].Check != `!eq` {
t.Errorf(`Checknames missing !, got "%s" and "%s"`, errs[0].Check, errs[1].Check)
}
}