-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidators.go
More file actions
88 lines (78 loc) · 2.06 KB
/
validators.go
File metadata and controls
88 lines (78 loc) · 2.06 KB
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
package cli
import (
"errors"
"fmt"
"slices"
"strings"
)
type ValidateFunc func(string) error
var SnakeCase = func(input string) error {
if len(input) == 0 {
return errors.New("input cannot be empty")
}
// input must start with a letter and contain only letters, numbers, and underscores
if len(input) > 0 && input[0] < 'a' || input[0] > 'z' {
return errors.New("field name must start with a lowercase letter")
}
for _, c := range input {
if c < 'a' || c > 'z' {
if c < '0' || c > '9' {
if c != '_' {
return errors.New("field name must contain only lowercase letters, numbers, and underscores")
}
}
}
}
return nil
}
var SnakeCaseEmptyAllowed = func(input string) error {
if len(input) == 0 {
return nil
}
// input must start with a letter and contain only letters, numbers, and underscores
if len(input) > 0 && input[0] < 'a' || input[0] > 'z' {
return errors.New("field name must start with a lowercase letter")
}
for _, c := range input {
if c < 'a' || c > 'z' {
if c < '0' || c > '9' {
if c != '_' {
return errors.New("field name must contain only lowercase letters, numbers, and underscores")
}
}
}
}
return nil
}
var NotIn = func(ignoreList []string, message string, validators ...ValidateFunc) ValidateFunc {
return func(input string) error {
if slices.Contains(ignoreList, strings.ToLower(input)) {
if message == "" {
return errors.New(fmt.Sprintf("input must not contain %s", strings.Join(ignoreList, ",")))
}
return errors.New(message)
}
for _, v := range validators {
if err := v(input); err != nil {
return err
}
}
return nil
}
}
var In = func(allowList []string, message string, validators ...ValidateFunc) ValidateFunc {
return func(input string) error {
if slices.Contains(allowList, strings.ToLower(input)) {
if message == "" {
return errors.New(fmt.Sprintf("input must contain %s", strings.Join(allowList, ",")))
}
return errors.New(message)
}
for _, v := range validators {
if err := v(input); err != nil {
return err
}
}
return nil
}
}