github.com/wangyougui/gf/v2@v2.6.5/util/gvalid/internal/builtin/builtin_max_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/wangyougui/gf.
     6  
     7  package builtin
     8  
     9  import (
    10  	"errors"
    11  	"strconv"
    12  
    13  	"github.com/wangyougui/gf/v2/text/gstr"
    14  	"github.com/wangyougui/gf/v2/util/gconv"
    15  )
    16  
    17  // RuleMaxLength implements `max-length` rule:
    18  // Length is equal or lesser than :max.
    19  // The length is calculated using unicode string, which means one chinese character or letter both has the length of 1.
    20  //
    21  // Format: max-length:max
    22  type RuleMaxLength struct{}
    23  
    24  func init() {
    25  	Register(RuleMaxLength{})
    26  }
    27  
    28  func (r RuleMaxLength) Name() string {
    29  	return "max-length"
    30  }
    31  
    32  func (r RuleMaxLength) Message() string {
    33  	return "The {field} value `{value}` length must be equal or lesser than {max}"
    34  }
    35  
    36  func (r RuleMaxLength) Run(in RunInput) error {
    37  	var (
    38  		valueRunes = gconv.Runes(in.Value.String())
    39  		valueLen   = len(valueRunes)
    40  	)
    41  	max, err := strconv.Atoi(in.RulePattern)
    42  	if valueLen > max || err != nil {
    43  		return errors.New(gstr.Replace(in.Message, "{max}", strconv.Itoa(max)))
    44  	}
    45  	return nil
    46  }