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