-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rule.go
59 lines (53 loc) · 1.4 KB
/
rule.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package valis
import (
"github.com/soranoba/valis/code"
"reflect"
)
type (
// Rule is an interface where verification contents are defined.
Rule interface {
Validate(validator *Validator, value interface{})
}
// CombinationRule is a high-order function that returns a new Rule.
CombinationRule func(rules ...Rule) Rule
)
type (
// Validatable will be delegated the validation by the ValidatableRule if implemented.
Validatable interface {
Validate() error
}
// ValidatableWithValidator will be delegated the validation by the ValidatableRule if implemented.
ValidatableWithValidator interface {
Validate(validator *Validator)
}
)
type (
validatableRule struct{}
)
var (
// ValidatableRule is a rule that delegates to Validate methods when verifying.
// See also Validatable and ValidatableWithValidator.
ValidatableRule Rule = &validatableRule{}
)
func (rule *validatableRule) Validate(validator *Validator, value interface{}) {
val := reflect.ValueOf(value)
for {
if !(val.IsValid() && val.CanInterface()) {
return
}
if v, ok := val.Interface().(ValidatableWithValidator); ok {
v.Validate(validator)
return
}
if v, ok := val.Interface().(Validatable); ok {
if err := v.Validate(); err != nil {
validator.ErrorCollector().Add(validator.Location(), NewError(code.Custom, value, err))
}
return
}
if val.Kind() != reflect.Ptr {
break
}
val = val.Elem()
}
}