This repository has been archived by the owner on Dec 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LengthValidator.go
70 lines (61 loc) · 1.96 KB
/
LengthValidator.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
package ecms_validator
import (
"fmt"
"reflect"
)
type LengthValidatorOptions struct {
MessageFuncs *MessageFuncs
Min int64
Max int64
Inclusive bool
}
var DefaultLengthValidatorMessageFuncs MessageFuncs
func init() {
DefaultLengthValidatorMessageFuncs = MessageFuncs{
NotAValidType: func(options ValidatorOptions, x interface{}) string {
return fmt.Sprintf("%v is not a lengthable value type; "+
"Expected an array, a slice, a map, or a string value.", x)
},
NotWithinRange: func(options ValidatorOptions, x interface{}) string {
ops := options.(IntValidatorOptions) // We pass the message getter to IntRangeValidator instance hence ...
return fmt.Sprintf("%v is not within given length range of %d and %d", x, ops.Min, ops.Max)
},
}
}
func NewLengthValidatorOptions() LengthValidatorOptions {
return LengthValidatorOptions{
MessageFuncs: &DefaultLengthValidatorMessageFuncs,
Min: 0,
Max: 0,
Inclusive: true,
}
}
func LengthValidator (options LengthValidatorOptions) Validator {
ops := NewIntRangeValidatorOptions()
ops.Min = options.Min
ops.Max = options.Max
ops.Inclusive = options.Inclusive
ops.MessageFuncs = options.MessageFuncs
return func(x interface{}) (b bool, strings []string) {
rv := reflect.ValueOf(x)
var intToCheck int64
switch rv.Kind() {
case reflect.Invalid:
return false, []string{ops.GetErrorMessageByKey(NotAValidType, x)}
case reflect.Slice, reflect.Array, reflect.Map, reflect.String, reflect.Chan:
intToCheck = int64(rv.Len())
default:
return false, []string{ops.GetErrorMessageByKey(NotAValidType, x)}
}
return IntRangeValidator(ops)(intToCheck)
}
}
func (n LengthValidatorOptions) GetErrorMessageByKey(key int, x interface{}) string {
return GetErrorMessageByKey(n, key, x)
}
func (n LengthValidatorOptions) GetMessageFuncs() *MessageFuncs {
return n.MessageFuncs
}
func (n LengthValidatorOptions) GetValueObscurator() ValueObscurator {
return DefaultValueObscurator
}