Browse Source

Add not (!) to invert validation rules

master
Nise Void 12 months ago
parent
commit
cb4720cd31
Signed by: NiseVoid GPG Key ID: FBA14AC83EA602F3
2 changed files with 28 additions and 2 deletions
  1. +7
    -2
      validate.go
  2. +21
    -0
      validate_test.go

+ 7
- 2
validate.go 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
}


+ 21
- 0
validate_test.go 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)
}
}

Loading…
Cancel
Save