Compare commits

..

1 Commits

Author SHA1 Message Date
Nise Void 84ee3011ac
Add ValidateValuer 2020-11-04 18:09:07 +01:00
2 changed files with 25 additions and 19 deletions

View File

@ -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 {

View File

@ -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)
}