diff --git a/validate.go b/validate.go index d7d9ea3..59216c8 100644 --- a/validate.go +++ b/validate.go @@ -223,27 +223,28 @@ func getTagFuncs(i int, ft reflect.StructField, kind reflect.Kind, tags []string ptr = false } + var f validateCheck + if tag == `optional` { - rules = append(rules, rule{i, func(rv reflect.Value) ([]ValidationError, bool) { + f = func(rv reflect.Value) ([]ValidationError, bool) { check, _ := getTagFunc(`required`, ``, kind) return nil, check(rv, nil) - }}) - continue - } - - 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) == !not { - return nil, true + } + } else { + var not bool + if strings.HasPrefix(tag, `!`) { + not = true } - return []ValidationError{{Field: []Field{{nil, &ft}}, Check: tag, Value: value}}, false + check, val := getTagFunc(strings.TrimPrefix(tag, `!`), value, kind) + + f = func(rv reflect.Value) ([]ValidationError, bool) { + if check(rv, val) == !not { + return nil, true + } + + return []ValidationError{{Field: []Field{{nil, &ft}}, Check: tag, Value: value}}, false + } } if ptr { diff --git a/validate_test.go b/validate_test.go index 077297a..96a83b4 100644 --- a/validate_test.go +++ b/validate_test.go @@ -135,14 +135,19 @@ func (v val) ValidateValue() interface{} { func TestValidateValuer(t *testing.T) { type s struct { A val `validate:"required,lt=2"` + B val `validate:"optional,eq=3"` } - pass := s{val{Valid: true}} + pass1 := s{val{Valid: true}, val{}} + pass2 := s{val{Valid: true}, val{Int: 3, Valid: true}} fail1 := s{} - fail2 := s{val{Int: 2, Valid: true}} + fail2 := s{val{Int: 2, Valid: true}, val{}} + fail3 := s{val{Valid: true}, val{Int: 2, Valid: true}} - check(t, pass, 0) + check(t, pass1, 0) + check(t, pass2, 0) check(t, fail1, 1) check(t, fail2, 1) + check(t, fail3, 1) }