gf/util/gvalid/internal/builtin/builtin_length.go
2022-09-26 22:11:13 +08:00

65 lines
1.4 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 builtin
import (
"errors"
"strconv"
"strings"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv"
)
// RuleLength implements `length` rule:
// Length between :min and :max.
// The length is calculated using unicode string, which means one chinese character or letter both has the length of 1.
//
// Format: length:min,max
type RuleLength struct{}
func init() {
Register(RuleLength{})
}
func (r RuleLength) Name() string {
return "length"
}
func (r RuleLength) Message() string {
return "The {field} value `{value}` length must be between {min} and {max}"
}
func (r RuleLength) Run(in RunInput) error {
var (
valueRunes = gconv.Runes(in.Value.String())
valueLen = len(valueRunes)
)
var (
min = 0
max = 0
array = strings.Split(in.RulePattern, ",")
)
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 {
return errors.New(gstr.ReplaceByMap(in.Message, map[string]string{
"{min}": strconv.Itoa(min),
"{max}": strconv.Itoa(max),
}))
}
return nil
}