-
Notifications
You must be signed in to change notification settings - Fork 6
/
validator.go
47 lines (39 loc) · 987 Bytes
/
validator.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
package gody
import "fmt"
type ErrDuplicatedRule struct {
RuleDuplicated Rule
}
func (err *ErrDuplicatedRule) Error() string {
return fmt.Sprintf("rule %s is duplicated", err.RuleDuplicated.Name())
}
type Validator struct {
tagName string
rulesMap map[string]Rule
addedRules []Rule
}
func (v *Validator) AddRules(rs ...Rule) error {
for _, r := range rs {
if dr, exists := v.rulesMap[r.Name()]; exists {
return &ErrDuplicatedRule{RuleDuplicated: dr}
}
v.rulesMap[r.Name()] = r
}
v.addedRules = append(v.addedRules, rs...)
return nil
}
func (v *Validator) SetTagName(tn string) error {
if tn == "" {
return &ErrEmptyTagName{}
}
v.tagName = tn
return nil
}
func (v *Validator) Validate(b interface{}) (bool, error) {
return RawDefaultValidate(b, v.tagName, v.addedRules)
}
func NewValidator() *Validator {
tagName := DefaultTagName
rulesMap := make(map[string]Rule)
addedRules := make([]Rule, 0)
return &Validator{tagName, rulesMap, addedRules}
}