-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregex_validaktor.go
More file actions
54 lines (43 loc) · 1005 Bytes
/
regex_validaktor.go
File metadata and controls
54 lines (43 loc) · 1005 Bytes
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
package validaktor
import (
"errors"
"fmt"
"regexp"
"strings"
)
type (
regexValidator struct {
regex *regexp.Regexp
}
regexError struct {
message string
}
)
func newRegexValidatorError(message string) *regexError {
return ®exError{message: message}
}
func (e *regexError) Error() string {
return e.message
}
func (v *regexValidator) applyValidatorOptions(args ...string) error {
s := strings.Split(args[0], "=")
if len(s) != 2 {
return fmt.Errorf("regexValidator: apply options cannot find regex rules after '='")
}
rgx, err := regexp.Compile(s[1])
if err != nil {
return fmt.Errorf("regexValidator: apply options err: %w", err)
}
v.regex = rgx
return nil
}
func (v *regexValidator) validate(data interface{}) (bool, error) {
s, ok := data.(string)
if !ok {
return false, errors.New("data input is not valid")
}
if ok = v.regex.MatchString(s); !ok {
return false, newRegexValidatorError(fmt.Sprintf("%s not match in %s", s, v.regex))
}
return true, nil
}