github.com/wangyougui/gf/v2@v2.6.5/util/gvalid/internal/builtin/builtin_different.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 // RuleDifferent implements `different` rule: 19 // Value should be different from value of field. 20 // 21 // Format: different:field 22 type RuleDifferent struct{} 23 24 func init() { 25 Register(RuleDifferent{}) 26 } 27 28 func (r RuleDifferent) Name() string { 29 return "different" 30 } 31 32 func (r RuleDifferent) Message() string { 33 return "The {field} value `{value}` must be different from field {field1} value `{value1}`" 34 } 35 36 func (r RuleDifferent) Run(in RunInput) error { 37 var ( 38 ok = true 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 nil 51 } 52 return errors.New(gstr.ReplaceByMap(in.Message, map[string]string{ 53 "{field1}": fieldName, 54 "{value1}": gconv.String(fieldValue), 55 })) 56 }