-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstdvalidators.go
98 lines (87 loc) · 2.11 KB
/
stdvalidators.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
package typutil
import (
"errors"
"fmt"
"net/netip"
"reflect"
)
func init() {
SetValidator("not_empty", validateNotEmpty)
SetValidatorArgs("minlength", validateMinLength)
SetValidatorArgs("maxlength", validateMaxLength)
SetValidator("ip_address", validateIpAddr)
SetValidator("hex6color", validateHex6Color)
SetValidator("hex64", validateHex64)
}
func validateNotEmpty(v any) error {
switch t := v.(type) {
case string:
if len(t) == 0 {
return ErrEmptyValue
}
return nil
default:
s := reflect.ValueOf(v)
if s.Kind() == reflect.Pointer {
return validateNotEmpty(s.Elem().Interface())
}
// AsBool will return true if value is non zero, non empty
if AsBool(v) {
return nil
}
return ErrEmptyValue
}
}
func validateMinLength(v string, ln int) error {
if len(v) < ln {
return fmt.Errorf("string must be at least %d characters", ln)
}
return nil
}
func validateMaxLength(v string, ln int) error {
if len(v) > ln {
return fmt.Errorf("string must be at most %d characters", ln)
}
return nil
}
func validateIpAddr(ip string) error {
if ip == "" {
return nil
}
_, err := netip.ParseAddr(ip)
return err
}
func validateHex6Color(color *string) error {
// 6 digits hex color, for example 336699
// if a # is found in first position it will be trimmed. If value is empty no error will be returned (chain with not_empty to check emptyness too)
if *color == "" {
return nil
}
if (*color)[0] == '#' {
*color = (*color)[1:]
}
if len(*color) != 6 {
return errors.New("expecting 6 digits hex color")
}
for _, n := range *color {
if n < '0' && n > '9' && n < 'a' && n > 'f' && n < 'A' && n > 'F' {
return errors.New("invalid hex char in color")
}
}
return nil
}
// validateHex64 ensures a given string is exactly 64 hexadecimal characters, for example a value of a 256bits hash such as sha256
func validateHex64(hex string) error {
if hex == "" {
return nil
}
if len(hex) != 64 {
return errors.New("expected 64 hex chars")
}
for _, n := range hex {
if n < '0' && n > '9' && n < 'a' && n > 'f' && n < 'A' && n > 'F' {
return errors.New("invalid hex char")
}
}
return nil
}