/
gvalid_validator_rule_range.go
64 lines (58 loc) · 1.8 KB
/
gvalid_validator_rule_range.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
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gvalid
import (
"strconv"
"strings"
)
// checkRange checks `value` using range rules.
func (v *Validator) checkRange(value, ruleKey, ruleVal string, customMsgMap map[string]string) string {
msg := ""
switch ruleKey {
// Value range.
case "between":
array := strings.Split(ruleVal, ",")
min := float64(0)
max := float64(0)
if len(array) > 0 {
if v, err := strconv.ParseFloat(strings.TrimSpace(array[0]), 10); err == nil {
min = v
}
}
if len(array) > 1 {
if v, err := strconv.ParseFloat(strings.TrimSpace(array[1]), 10); err == nil {
max = v
}
}
valueF, err := strconv.ParseFloat(value, 10)
if valueF < min || valueF > max || err != nil {
msg = v.getErrorMessageByRule(ruleKey, customMsgMap)
msg = strings.Replace(msg, ":min", strconv.FormatFloat(min, 'f', -1, 64), -1)
msg = strings.Replace(msg, ":max", strconv.FormatFloat(max, 'f', -1, 64), -1)
}
// Min value.
case "min":
var (
min, err1 = strconv.ParseFloat(ruleVal, 10)
valueN, err2 = strconv.ParseFloat(value, 10)
)
if valueN < min || err1 != nil || err2 != nil {
msg = v.getErrorMessageByRule(ruleKey, customMsgMap)
msg = strings.Replace(msg, ":min", strconv.FormatFloat(min, 'f', -1, 64), -1)
}
// Max value.
case "max":
var (
max, err1 = strconv.ParseFloat(ruleVal, 10)
valueN, err2 = strconv.ParseFloat(value, 10)
)
if valueN > max || err1 != nil || err2 != nil {
msg = v.getErrorMessageByRule(ruleKey, customMsgMap)
msg = strings.Replace(msg, ":max", strconv.FormatFloat(max, 'f', -1, 64), -1)
}
}
return msg
}