github.com/wangyougui/gf/v2@v2.6.5/util/gvalid/internal/builtin/builtin_same.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 "strings" 12 13 "github.com/wangyougui/gf/v2/text/gstr" 14 "github.com/wangyougui/gf/v2/util/gconv" 15 "github.com/wangyougui/gf/v2/util/gutil" 16 ) 17 18 // RuleSame implements `same` rule: 19 // Value should be the same as value of field. 20 // 21 // Format: same:field 22 type RuleSame struct{} 23 24 func init() { 25 Register(RuleSame{}) 26 } 27 28 func (r RuleSame) Name() string { 29 return "same" 30 } 31 32 func (r RuleSame) Message() string { 33 return "The {field} value `{value}` must be the same as field {field1} value `{value1}`" 34 } 35 36 func (r RuleSame) Run(in RunInput) error { 37 var ( 38 ok bool 39 value = in.Value.String() 40 ) 41 fieldName, fieldValue := gutil.MapPossibleItemByKey(in.Data.Map(), in.RulePattern) 42 if fieldValue != nil { 43 if in.Option.CaseInsensitive { 44 ok = strings.EqualFold(value, gconv.String(fieldValue)) 45 } else { 46 ok = strings.Compare(value, gconv.String(fieldValue)) == 0 47 } 48 } 49 if !ok { 50 return errors.New(gstr.ReplaceByMap(in.Message, map[string]string{ 51 "{field1}": fieldName, 52 "{value1}": gconv.String(fieldValue), 53 })) 54 } 55 return nil 56 }