github.com/gogf/gf/v2@v2.7.4/util/gvalid/internal/builtin/builtin_between.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 ) 16 17 // RuleBetween implements `between` rule: 18 // Range between :min and :max. It supports both integer and float. 19 // 20 // Format: between:min,max 21 type RuleBetween struct{} 22 23 func init() { 24 Register(RuleBetween{}) 25 } 26 27 func (r RuleBetween) Name() string { 28 return "between" 29 } 30 31 func (r RuleBetween) Message() string { 32 return "The {field} value `{value}` must be between {min} and {max}" 33 } 34 35 func (r RuleBetween) Run(in RunInput) error { 36 var ( 37 array = strings.Split(in.RulePattern, ",") 38 min = float64(0) 39 max = float64(0) 40 ) 41 if len(array) > 0 { 42 if v, err := strconv.ParseFloat(strings.TrimSpace(array[0]), 10); err == nil { 43 min = v 44 } 45 } 46 if len(array) > 1 { 47 if v, err := strconv.ParseFloat(strings.TrimSpace(array[1]), 10); err == nil { 48 max = v 49 } 50 } 51 valueF, err := strconv.ParseFloat(in.Value.String(), 10) 52 if valueF < min || valueF > max || err != nil { 53 return errors.New(gstr.ReplaceByMap(in.Message, map[string]string{ 54 "{min}": strconv.FormatFloat(min, 'f', -1, 64), 55 "{max}": strconv.FormatFloat(max, 'f', -1, 64), 56 })) 57 } 58 return nil 59 }