-
Notifications
You must be signed in to change notification settings - Fork 4
/
validate.go
99 lines (86 loc) · 2.51 KB
/
validate.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
package golden
import (
"io/fs"
"strconv"
"strings"
"github.com/ahmetb/go-linq/v3"
"github.com/go-playground/validator/v10"
)
var Validate = validator.New(validator.WithRequiredStructEnabled())
func registerValidator() {
_ = Validate.RegisterValidation("conflict_with", validateConflictWith)
_ = Validate.RegisterValidation("at_least_one_of", validateAtLeastOneOf)
_ = Validate.RegisterValidation("required_with", validateRequiredWith)
_ = Validate.RegisterValidation("all_string_in_slice", validateAllStringInSlice)
_ = Validate.RegisterValidation("file_mode", validateFileMode)
}
func validateFileMode(fl validator.FieldLevel) bool {
field := fl.Field().Interface()
num, ok := field.(fs.FileMode)
if !ok {
return false
}
mode, err := strconv.ParseUint(strconv.Itoa(int(num)), 8, 32)
if err != nil {
return false
}
return uint32(mode) <= uint32(fs.ModePerm)
}
func validateAllStringInSlice(fl validator.FieldLevel) bool {
candidatesQuery := linq.From(strings.Split(fl.Param(), " "))
parentStruct := fl.Parent()
fieldName := fl.FieldName()
thisField := parentStruct.FieldByName(fieldName)
if !thisField.IsValid() || thisField.IsZero() {
return true
}
values, ok := thisField.Interface().([]string)
if !ok {
return false
}
valuesQuery := linq.From(values)
return !valuesQuery.Except(candidatesQuery).Any()
}
func validateConflictWith(fl validator.FieldLevel) bool {
conflictWith := strings.Split(fl.Param(), " ")
parentStruct := fl.Parent()
fieldName := fl.FieldName()
thisField := parentStruct.FieldByName(fieldName)
if !thisField.IsValid() || thisField.IsZero() {
return true
}
for _, anotherField := range conflictWith {
field := parentStruct.FieldByName(anotherField)
if field.IsValid() && !field.IsZero() {
return false
}
}
return true
}
func validateRequiredWith(fl validator.FieldLevel) bool {
requiredWith := strings.Split(fl.Param(), " ")
parentStruct := fl.Parent()
fieldName := fl.FieldName()
thisField := parentStruct.FieldByName(fieldName)
if !thisField.IsValid() || thisField.IsZero() {
return true
}
for _, anotherField := range requiredWith {
field := parentStruct.FieldByName(anotherField)
if !field.IsValid() || field.IsZero() {
return false
}
}
return true
}
func validateAtLeastOneOf(fl validator.FieldLevel) bool {
atLeastOneOf := strings.Split(fl.Param(), " ")
parentStruct := fl.Parent()
for _, fieldName := range atLeastOneOf {
field := parentStruct.FieldByName(fieldName)
if field.IsValid() && !field.IsZero() {
return true
}
}
return false
}