This repository has been archived by the owner on Dec 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RegexValidator.go
72 lines (62 loc) · 1.57 KB
/
RegexValidator.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
67
68
69
70
71
72
package ecms_validator
import (
"fmt"
"regexp"
)
type RegexValidatorOptions struct {
Pattern *regexp.Regexp
MessageFuncs *MessageFuncs
}
var RegexValidatorMessageFuncs *MessageFuncs
func init() {
RegexValidatorMessageFuncs = &MessageFuncs{
DoesNotMatchPattern: func(options ValidatorOptions, x interface{}) string {
ops := options.(RegexValidatorOptions)
var pattern string
if ops.Pattern != nil {
pattern = ops.Pattern.String()
}
return fmt.Sprintf("%v does not match required pattern `%v`", x, pattern)
},
}
}
func NewRegexValidatorOptions () RegexValidatorOptions {
return RegexValidatorOptions{
Pattern: nil,
MessageFuncs: RegexValidatorMessageFuncs,
}
}
func RegexValidator(options RegexValidatorOptions) Validator {
return func(x interface{}) (bool, []string) {
if options.Pattern == nil {
isValid := x == nil
if !isValid {
return false, []string {
options.GetErrorMessageByKey(DoesNotMatchPattern, x),
}
}
return true, nil
}
var match bool
if options.Pattern != nil && x == nil {
match = false
} else {
match = options.Pattern.Match([]byte(x.(string)))
}
if match != true {
return false, []string{
options.GetErrorMessageByKey(DoesNotMatchPattern, x),
}
}
return true, nil
}
}
func (n RegexValidatorOptions) GetErrorMessageByKey(key int, x interface{}) string {
return GetErrorMessageByKey(n, key, x)
}
func (n RegexValidatorOptions) GetMessageFuncs() *MessageFuncs {
return n.MessageFuncs
}
func (n RegexValidatorOptions) GetValueObscurator() ValueObscurator {
return DefaultValueObscurator
}