gf/util/gvalid/gvalid_validator_rule_length.go

64 lines
1.7 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 (
"github.com/gogf/gf/util/gconv"
"strconv"
"strings"
)
2020-05-16 13:31:24 +08:00
// checkLength checks <value> using length rules.
2020-05-10 16:48:00 +08:00
// The length is calculated using unicode string, which means one chinese character or letter
// both has the length of 1.
2021-01-12 10:46:39 +08:00
func (v *Validator) checkLength(value, ruleKey, ruleVal string, customMsgMap map[string]string) string {
2020-05-10 10:56:11 +08:00
var (
msg = ""
runeArray = gconv.Runes(value)
valueLen = len(runeArray)
)
switch ruleKey {
case "length":
2020-05-10 16:48:00 +08:00
var (
min = 0
max = 0
array = strings.Split(ruleVal, ",")
)
2020-05-10 10:56:11 +08:00
if len(array) > 0 {
if v, err := strconv.Atoi(strings.TrimSpace(array[0])); err == nil {
min = v
}
}
if len(array) > 1 {
if v, err := strconv.Atoi(strings.TrimSpace(array[1])); err == nil {
max = v
}
}
if valueLen < min || valueLen > max {
2021-01-12 10:46:39 +08:00
msg = v.getErrorMessageByRule(ruleKey, customMsgMap)
2020-05-10 10:56:11 +08:00
msg = strings.Replace(msg, ":min", strconv.Itoa(min), -1)
msg = strings.Replace(msg, ":max", strconv.Itoa(max), -1)
return msg
}
case "min-length":
2020-05-16 13:31:24 +08:00
min, err := strconv.Atoi(ruleVal)
if valueLen < min || err != nil {
2021-01-12 10:46:39 +08:00
msg = v.getErrorMessageByRule(ruleKey, customMsgMap)
2020-05-16 13:31:24 +08:00
msg = strings.Replace(msg, ":min", strconv.Itoa(min), -1)
2020-05-10 10:56:11 +08:00
}
case "max-length":
2020-05-16 13:31:24 +08:00
max, err := strconv.Atoi(ruleVal)
if valueLen > max || err != nil {
2021-01-12 10:46:39 +08:00
msg = v.getErrorMessageByRule(ruleKey, customMsgMap)
2020-05-16 13:31:24 +08:00
msg = strings.Replace(msg, ":max", strconv.Itoa(max), -1)
2020-05-10 10:56:11 +08:00
}
}
return msg
}