-
Notifications
You must be signed in to change notification settings - Fork 0
/
strings.go
85 lines (68 loc) · 1.59 KB
/
strings.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
package validator
import (
"errors"
"regexp"
"unicode/utf8"
)
type StringValid func(s string) error
func stringExecuter(s string, valids ...StringValid) error {
for _, v := range valids {
if err := v(s); err != nil {
return err
}
}
return nil
}
func StringRequire(s string, valids ...StringValid) Validation {
return func() error {
if utf8.RuneCountInString(s) == 0 {
return ErrRequired
}
return stringExecuter(s, valids...)
}
}
func StringOption(s string, valids ...StringValid) Validation {
return func() error {
if utf8.RuneCountInString(s) == 0 {
return nil
}
return stringExecuter(s, valids...)
}
}
var ErrWrongLength = errors.New("wrong length")
func Length(length int) StringValid {
return func(s string) error {
if utf8.RuneCountInString(s) != length {
return ErrWrongLength
}
return nil
}
}
var ErrTooShort = errors.New("too short")
func Longer(length int) StringValid {
return func(s string) error {
if utf8.RuneCountInString(s) < length {
return ErrTooShort
}
return nil
}
}
var ErrTooLong = errors.New("too long")
func Shorter(length int) StringValid {
return func(s string) error {
if utf8.RuneCountInString(s) > length {
return ErrTooLong
}
return nil
}
}
var ErrEmailInvalid = errors.New("invalid email format")
func Email() StringValid {
emailRegex := regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
return func(s string) error {
if !emailRegex.MatchString(s) {
return ErrEmailInvalid
}
return nil
}
}