-
Notifications
You must be signed in to change notification settings - Fork 1
/
validator.go
63 lines (51 loc) · 1.52 KB
/
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
package validator
import "regexp"
// Declare a regular expression for sanity checking the format of email addresses.
var (
EmailRX = regexp.MustCompile("^[a-zA-Z0-9]*")
)
// Define a new Validator type which contains a map of validation errors.
type Validator struct {
Errors map[string]string
}
// New is a helper which creates a new Validator instance with an empty errors map.
func New() *Validator {
return &Validator{Errors: make(map[string]string)}
}
// Valid returns true if the errors map doesn't contain any entries.
func (v *Validator) Valid() bool {
return len(v.Errors) == 0
}
// AddError adds an error message to the map.
func (v *Validator) AddError(key, message string) {
if _, exists := v.Errors[key]; !exists {
v.Errors[key] = message
}
}
// Check adds an error message to the map only if a validation check is not ok.
func (v *Validator) Check(ok bool, key, message string) {
if !ok {
v.AddError(key, message)
}
}
// In returns true if a specific value is in a list of strings.
func In(value string, list ...string) bool {
for i := range list {
if value == list[i] {
return true
}
}
return false
}
// Matches returns true if a string value matches a specific regexp pattern.
func Matches(value string, rx *regexp.Regexp) bool {
return rx.MatchString(value)
}
// Unique returns true if all string values in a slice are unique.
func Unique(values []string) bool {
uniqueValues := make(map[string]bool)
for _, value := range values {
uniqueValues[value] = true
}
return len(values) == len(uniqueValues)
}