-
Notifications
You must be signed in to change notification settings - Fork 2
/
validation.go
93 lines (76 loc) · 1.49 KB
/
validation.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package forms
import (
"regexp"
)
type Validation interface {
validate()
setValue(val string)
getErr() string
isValid() bool
}
// Required Checks whether any value is set
type Required struct {
Value string
Err string
Valid bool
}
// Checks for a specific length
type LengthValidation struct {
Value string
Err string
Valid bool
Len int
}
// Custom Regex validation
type RegexValidation struct {
Value string
Err string
Valid bool
Regex string
}
// Methods for the Required validation struct
func (r *Required) validate() {
// We only follow the happy path here because go sets Valid as
// its null value (false)
if len(r.Value) > 0 {
r.Valid = true
}
}
func (r *Required) setValue(val string) {
r.Value = val
}
func (r Required) getErr() string {
return r.Err
}
func (r Required) isValid() bool {
return r.Valid
}
// Methods for the Length validation struct
func (l *LengthValidation) validate() {
if len(l.Value) == l.Len {
l.Valid = true
}
}
func (l *LengthValidation) setValue(val string) {
l.Value = val
}
func (l LengthValidation) getErr() string {
return l.Err
}
func (l LengthValidation) isValid() bool {
return l.Valid
}
// Methods for the Regex Validation struct
func (r *RegexValidation) validate() {
match, _ := regexp.MatchString(r.Regex, r.Value)
r.Valid = match
}
func (r *RegexValidation) setValue(val string) {
r.Value = val
}
func (r RegexValidation) getErr() string {
return r.Err
}
func (r RegexValidation) isValid() bool {
return r.Valid
}