/
string.go
executable file
·107 lines (95 loc) · 2.6 KB
/
string.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package ursa
import (
"net/mail"
"regexp"
)
// ursa is a zod inspired validation library for Go.
// Copyright (C) 2023 John Dudmesh
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
type stringValidatorOpt = parseOpt[string]
func String(opts ...any) genericValidator[string] {
return validatorFactory[string](opts...)
}
func MinLength(min int, message ...string) stringValidatorOpt {
return func(val *string) *parseError {
if val == nil {
return nil
}
if len(*val) < min {
if len(message) > 0 {
return &parseError{message: message[0]}
}
return &parseError{message: "string too short"}
}
return nil
}
}
func MaxLength(max int, message ...string) stringValidatorOpt {
return func(val *string) *parseError {
if val == nil {
return nil
}
if len(*val) > max {
if len(message) > 0 {
return &parseError{message: message[0]}
}
return &parseError{message: "string too long"}
}
return nil
}
}
func Matches(patt string, message ...string) stringValidatorOpt {
re, err := regexp.Compile(patt)
return func(val *string) *parseError {
if val == nil {
return nil
}
if err != nil {
return &parseError{message: "invalid regexp pattern", inner: []error{err}}
}
if !re.MatchString(*val) {
if len(message) > 0 {
return &parseError{message: message[0]}
}
return &parseError{message: "string does not match pattern"}
}
return nil
}
}
func Email(message ...string) stringValidatorOpt {
return func(val *string) *parseError {
if val == nil {
return nil
}
_, err := mail.ParseAddress(*val)
if err != nil {
if len(message) > 0 {
return &parseError{message: message[0], inner: []error{err}}
}
return &parseError{message: "invalid email address", inner: []error{err}}
}
return nil
}
}
func Enum(values ...string) stringValidatorOpt {
return func(val *string) *parseError {
if val == nil {
return nil
}
for _, v := range values {
if v == *val {
return nil
}
}
return &parseError{message: "value not found in enum", inner: []error{}}
}
}