gf/util/gvalid/gvalid_validator_rule_length.go

73 lines
2.0 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"
2021-11-13 23:30:31 +08:00
"github.com/gogf/gf/v2/util/gconv"
2020-05-10 10:56:11 +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.
func (v *Validator) checkLength(ctx context.Context, 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 {
msg = v.getErrorMessageByRule(ctx, ruleKey, customMsgMap)
msg = strings.Replace(msg, "{min}", strconv.Itoa(min), -1)
msg = strings.Replace(msg, "{max}", strconv.Itoa(max), -1)
2020-05-10 10:56:11 +08:00
return msg
}
case "min-length":
2020-05-16 13:31:24 +08:00
min, err := strconv.Atoi(ruleVal)
if valueLen < min || err != nil {
msg = v.getErrorMessageByRule(ctx, ruleKey, customMsgMap)
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 {
msg = v.getErrorMessageByRule(ctx, ruleKey, customMsgMap)
msg = strings.Replace(msg, "{max}", strconv.Itoa(max), -1)
2020-05-10 10:56:11 +08:00
}
2021-05-29 12:15:37 +08:00
case "size":
size, err := strconv.Atoi(ruleVal)
if valueLen != size || err != nil {
msg = v.getErrorMessageByRule(ctx, ruleKey, customMsgMap)
msg = strings.Replace(msg, "{size}", strconv.Itoa(size), -1)
2021-05-29 12:15:37 +08:00
}
2020-05-10 10:56:11 +08:00
}
return msg
}