Files
gf/util/gvalid/gvalid_validator_rule_range.go

66 lines
1.9 KiB
Go
Raw Normal View History

2021-01-12 10:46:39 +08:00
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
2020-05-10 10:56:11 +08:00
//
// 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 (
"context"
2020-05-10 10:56:11 +08:00
"strconv"
"strings"
)
// checkRange checks `value` using range rules.
func (v *Validator) checkRange(ctx context.Context, value, ruleKey, ruleVal string, customMsgMap map[string]string) string {
2020-05-10 10:56:11 +08:00
msg := ""
switch ruleKey {
2020-05-10 17:49:23 +08:00
// Value range.
2020-05-10 10:56:11 +08:00
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
}
}
2021-01-12 10:46:39 +08:00
valueF, err := strconv.ParseFloat(value, 10)
if valueF < min || valueF > max || err != nil {
msg = v.getErrorMessageByRule(ctx, 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)
2020-05-10 10:56:11 +08:00
}
2020-05-10 17:49:23 +08:00
// Min value.
2020-05-10 10:56:11 +08:00
case "min":
2020-05-16 13:31:24 +08:00
var (
min, err1 = strconv.ParseFloat(ruleVal, 10)
valueN, err2 = strconv.ParseFloat(value, 10)
)
if valueN < min || err1 != nil || err2 != nil {
msg = v.getErrorMessageByRule(ctx, ruleKey, customMsgMap)
msg = strings.Replace(msg, "{min}", strconv.FormatFloat(min, 'f', -1, 64), -1)
2020-05-10 10:56:11 +08:00
}
2020-05-10 17:49:23 +08:00
// Max value.
2020-05-10 10:56:11 +08:00
case "max":
2020-05-16 13:31:24 +08:00
var (
max, err1 = strconv.ParseFloat(ruleVal, 10)
valueN, err2 = strconv.ParseFloat(value, 10)
)
if valueN > max || err1 != nil || err2 != nil {
msg = v.getErrorMessageByRule(ctx, ruleKey, customMsgMap)
msg = strings.Replace(msg, "{max}", strconv.FormatFloat(max, 'f', -1, 64), -1)
2020-05-10 10:56:11 +08:00
}
2020-05-16 13:31:24 +08:00
2020-05-10 10:56:11 +08:00
}
return msg
}