forked from Fuyu/validate
Add not (!) to invert validation rules
This commit is contained in:
parent
f79b7c6649
commit
cb4720cd31
@ -206,10 +206,15 @@ func getTagFuncs(i int, ft reflect.StructField, kind reflect.Kind, tags []string
|
|||||||
continue
|
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) {
|
f := func(rv reflect.Value) ([]ValidationError, bool) {
|
||||||
if check(rv, val) {
|
if check(rv, val) == !not {
|
||||||
return nil, true
|
return nil, true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -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)
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user