-
Notifications
You must be signed in to change notification settings - Fork 0
/
max_validator.go
56 lines (48 loc) · 1.09 KB
/
max_validator.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
package validators
import (
"errors"
"fmt"
)
// Checks if the value is greater than the specified maximum value.
//
// Configuration parameters:
// - max(int | int32 | int64 | float32 | float64): maximum value that the value must have.
// - errorMessage (string): custom error message (optional).
//
// Input value (int | int32 | int64 | float32 | float64): value to be validated.
//
// Usage examples:
//
// value := 3
// v.Max(5)(value) // Output: nil, false
//
// value := 6
// v.Max(5)(value) // Output: [error message], false
// v.Max(5, "error")(value) // Output: "error", false
func Max(
max any,
errorMessage ...string,
) Validator {
var message string
val := 0.0
maxValue := convertToFloat64(max)
return func(value any) (error, bool) {
if len(errorMessage) != 0 {
message = errorMessage[0]
} else {
message = ""
}
if message == "" {
message = fmt.Sprintf(
"The maximum value is %v, but it received %v.",
max,
value,
)
}
val = convertToFloat64(value)
if val > maxValue {
return errors.New(message), false
}
return nil, false
}
}