-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstrfmt_validator.go
66 lines (56 loc) · 1.56 KB
/
strfmt_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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package validator
import (
"context"
"reflect"
"regexp"
"github.com/go-courier/validator/errors"
)
func NewRegexpStrfmtValidator(regexpStr string, name string, aliases ...string) *StrfmtValidator {
re := regexp.MustCompile(regexpStr)
validate := func(v interface{}) error {
if !re.MatchString(v.(string)) {
return &errors.NotMatchError{
Target: name,
Current: v,
Pattern: re,
}
}
return nil
}
return NewStrfmtValidator(validate, name, aliases...)
}
func NewStrfmtValidator(validate func(v interface{}) error, name string, aliases ...string) *StrfmtValidator {
return &StrfmtValidator{
names: append([]string{name}, aliases...),
validate: validate,
}
}
type StrfmtValidator struct {
names []string
validate func(v interface{}) error
}
func (validator *StrfmtValidator) String() string {
return "@" + validator.names[0]
}
func (validator *StrfmtValidator) Names() []string {
return validator.names
}
func (validator StrfmtValidator) New(ctx context.Context, rule *Rule) (Validator, error) {
return &validator, validator.TypeCheck(rule)
}
func (validator *StrfmtValidator) TypeCheck(rule *Rule) error {
if rule.Type.Kind() == reflect.String {
return nil
}
return errors.NewUnsupportedTypeError(rule.String(), validator.String())
}
func (validator *StrfmtValidator) Validate(v interface{}) error {
if rv, ok := v.(reflect.Value); ok && rv.CanInterface() {
v = rv.Interface()
}
s, ok := v.(string)
if !ok {
return errors.NewUnsupportedTypeError(reflect.TypeOf(v).String(), validator.String())
}
return validator.validate(s)
}