-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathvalidate_required.go
49 lines (39 loc) · 1.3 KB
/
validate_required.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
package changeset
import (
"strings"
)
// ValidateRequiredErrorMessage is the default error message for ValidateRequired.
var ValidateRequiredErrorMessage = "{field} is required"
// isZeroer is the interface that wraps the basic isZero method.
type isZeroer interface {
IsZero() bool
}
// ValidateRequired validates that one or more fields are present in the changeset.
// It'll add error to changeset if field in the changes is nil or string made only of whitespace.
func ValidateRequired(ch *Changeset, fields []string, opts ...Option) {
options := Options{
message: ValidateRequiredErrorMessage,
}
options.apply(opts)
for _, f := range fields {
val, exist := ch.changes[f]
// check values if it's not exist in changeset when changeOnly is false and changeset values are all zero value
if !exist && !options.changeOnly && !ch.zero {
val, exist = ch.values[f]
}
str, isStr := val.(string)
if exist && isStr && strings.TrimSpace(str) != "" {
continue
}
zeroer, isZeroer := val.(isZeroer)
if exist && isZeroer && !zeroer.IsZero() {
continue
}
// Only check nil value if val is not string and isZeroer since it has been checked before.
if exist && !isStr && !isZeroer && val != nil {
continue
}
msg := strings.Replace(options.message, "{field}", f, 1)
AddError(ch, f, msg)
}
}