-
Notifications
You must be signed in to change notification settings - Fork 34
/
validator__strfmt.go
63 lines (52 loc) · 1.4 KB
/
validator__strfmt.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
package validator
import (
"context"
"reflect"
"regexp"
"github.com/machinefi/w3bstream/pkg/depends/kit/validator/errors"
)
type ValidateFunc func(interface{}) error
type StrFmt struct {
names []string
fn ValidateFunc
}
func NewStrfmtValidator(f ValidateFunc, name string, aliases ...string) *StrFmt {
return &StrFmt{append([]string{name}, aliases...), f}
}
func NewRegexpStrfmtValidator(expr string, name string, aliases ...string) *StrFmt {
regexpStrfmtPattern := regexp.MustCompile(expr)
f := func(v interface{}) error {
if !regexpStrfmtPattern.MatchString(v.(string)) {
return &errors.NotMatchError{
Target: name,
Current: v,
Pattern: regexpStrfmtPattern,
}
}
return nil
}
return NewStrfmtValidator(f, name, aliases...)
}
func (v *StrFmt) String() string { return "@" + v.names[0] }
func (v *StrFmt) Names() []string { return v.names }
func (v StrFmt) New(_ context.Context, r *Rule) (Validator, error) {
return &v, v.TypeCheck(r)
}
func (v *StrFmt) TypeCheck(r *Rule) error {
if r.Type.Kind() == reflect.String {
return nil
}
return errors.NewUnsupportedTypeError(r.String(), v.String())
}
func (v *StrFmt) Validate(val interface{}) error {
if rv, ok := val.(reflect.Value); ok && rv.CanInterface() {
val = rv.Interface()
}
str, ok := val.(string)
if !ok {
return errors.NewUnsupportedTypeError(
reflect.TypeOf(val).String(), v.String(),
)
}
return v.fn(str)
}