github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/validator/validator__strfmt.go (about) 1 package validator 2 3 import ( 4 "context" 5 "reflect" 6 "regexp" 7 8 "github.com/machinefi/w3bstream/pkg/depends/kit/validator/errors" 9 ) 10 11 type ValidateFunc func(interface{}) error 12 13 type StrFmt struct { 14 names []string 15 fn ValidateFunc 16 } 17 18 func NewStrfmtValidator(f ValidateFunc, name string, aliases ...string) *StrFmt { 19 return &StrFmt{append([]string{name}, aliases...), f} 20 } 21 22 func NewRegexpStrfmtValidator(expr string, name string, aliases ...string) *StrFmt { 23 regexpStrfmtPattern := regexp.MustCompile(expr) 24 f := func(v interface{}) error { 25 if !regexpStrfmtPattern.MatchString(v.(string)) { 26 return &errors.NotMatchError{ 27 Target: name, 28 Current: v, 29 Pattern: regexpStrfmtPattern, 30 } 31 } 32 return nil 33 } 34 return NewStrfmtValidator(f, name, aliases...) 35 } 36 37 func (v *StrFmt) String() string { return "@" + v.names[0] } 38 39 func (v *StrFmt) Names() []string { return v.names } 40 41 func (v StrFmt) New(_ context.Context, r *Rule) (Validator, error) { 42 return &v, v.TypeCheck(r) 43 } 44 45 func (v *StrFmt) TypeCheck(r *Rule) error { 46 if r.Type.Kind() == reflect.String { 47 return nil 48 } 49 return errors.NewUnsupportedTypeError(r.String(), v.String()) 50 } 51 52 func (v *StrFmt) Validate(val interface{}) error { 53 if rv, ok := val.(reflect.Value); ok && rv.CanInterface() { 54 val = rv.Interface() 55 } 56 str, ok := val.(string) 57 if !ok { 58 return errors.NewUnsupportedTypeError( 59 reflect.TypeOf(val).String(), v.String(), 60 ) 61 } 62 return v.fn(str) 63 }