gf/util/gvalid/gvalid_validator_rule_length.go
2021-11-14 22:50:53 +08:00

73 lines
2.0 KiB
Go

// 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 (
"context"
"strconv"
"strings"
"github.com/gogf/gf/v2/util/gconv"
)
// checkLength checks `value` using length rules.
// 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 {
var (
msg = ""
runeArray = gconv.Runes(value)
valueLen = len(runeArray)
)
switch ruleKey {
case "length":
var (
min = 0
max = 0
array = strings.Split(ruleVal, ",")
)
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)
return msg
}
case "min-length":
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)
}
case "max-length":
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)
}
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)
}
}
return msg
}