github.com/gogf/gf@v1.16.9/util/gvalid/gvalid_validator_rule_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 gvalid
     8  
     9  import (
    10  	"github.com/gogf/gf/util/gconv"
    11  	"strconv"
    12  	"strings"
    13  )
    14  
    15  // checkLength checks `value` using length rules.
    16  // The length is calculated using unicode string, which means one chinese character or letter
    17  // both has the length of 1.
    18  func (v *Validator) checkLength(value, ruleKey, ruleVal string, customMsgMap map[string]string) string {
    19  	var (
    20  		msg       = ""
    21  		runeArray = gconv.Runes(value)
    22  		valueLen  = len(runeArray)
    23  	)
    24  	switch ruleKey {
    25  	case "length":
    26  		var (
    27  			min   = 0
    28  			max   = 0
    29  			array = strings.Split(ruleVal, ",")
    30  		)
    31  		if len(array) > 0 {
    32  			if v, err := strconv.Atoi(strings.TrimSpace(array[0])); err == nil {
    33  				min = v
    34  			}
    35  		}
    36  		if len(array) > 1 {
    37  			if v, err := strconv.Atoi(strings.TrimSpace(array[1])); err == nil {
    38  				max = v
    39  			}
    40  		}
    41  		if valueLen < min || valueLen > max {
    42  			msg = v.getErrorMessageByRule(ruleKey, customMsgMap)
    43  			msg = strings.Replace(msg, ":min", strconv.Itoa(min), -1)
    44  			msg = strings.Replace(msg, ":max", strconv.Itoa(max), -1)
    45  			return msg
    46  		}
    47  
    48  	case "min-length":
    49  		min, err := strconv.Atoi(ruleVal)
    50  		if valueLen < min || err != nil {
    51  			msg = v.getErrorMessageByRule(ruleKey, customMsgMap)
    52  			msg = strings.Replace(msg, ":min", strconv.Itoa(min), -1)
    53  		}
    54  
    55  	case "max-length":
    56  		max, err := strconv.Atoi(ruleVal)
    57  		if valueLen > max || err != nil {
    58  			msg = v.getErrorMessageByRule(ruleKey, customMsgMap)
    59  			msg = strings.Replace(msg, ":max", strconv.Itoa(max), -1)
    60  		}
    61  
    62  	case "size":
    63  		size, err := strconv.Atoi(ruleVal)
    64  		if valueLen != size || err != nil {
    65  			msg = v.getErrorMessageByRule(ruleKey, customMsgMap)
    66  			msg = strings.Replace(msg, ":size", strconv.Itoa(size), -1)
    67  		}
    68  	}
    69  	return msg
    70  }