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