github.com/gogf/gf/v2@v2.7.4/util/gvalid/internal/builtin/builtin_length.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package builtin
     8  
     9  import (
    10  	"errors"
    11  	"strconv"
    12  	"strings"
    13  
    14  	"github.com/gogf/gf/v2/text/gstr"
    15  	"github.com/gogf/gf/v2/util/gconv"
    16  )
    17  
    18  // RuleLength implements `length` rule:
    19  // Length between :min and :max.
    20  // The length is calculated using unicode string, which means one chinese character or letter both has the length of 1.
    21  //
    22  // Format: length:min,max
    23  type RuleLength struct{}
    24  
    25  func init() {
    26  	Register(RuleLength{})
    27  }
    28  
    29  func (r RuleLength) Name() string {
    30  	return "length"
    31  }
    32  
    33  func (r RuleLength) Message() string {
    34  	return "The {field} value `{value}` length must be between {min} and {max}"
    35  }
    36  
    37  func (r RuleLength) Run(in RunInput) error {
    38  	var (
    39  		valueRunes = gconv.Runes(in.Value.String())
    40  		valueLen   = len(valueRunes)
    41  	)
    42  	var (
    43  		min   = 0
    44  		max   = 0
    45  		array = strings.Split(in.RulePattern, ",")
    46  	)
    47  	if len(array) > 0 {
    48  		if v, err := strconv.Atoi(strings.TrimSpace(array[0])); err == nil {
    49  			min = v
    50  		}
    51  	}
    52  	if len(array) > 1 {
    53  		if v, err := strconv.Atoi(strings.TrimSpace(array[1])); err == nil {
    54  			max = v
    55  		}
    56  	}
    57  	if valueLen < min || valueLen > max {
    58  		return errors.New(gstr.ReplaceByMap(in.Message, map[string]string{
    59  			"{min}": strconv.Itoa(min),
    60  			"{max}": strconv.Itoa(max),
    61  		}))
    62  	}
    63  	return nil
    64  }