github.com/wangyougui/gf/v2@v2.6.5/util/gvalid/internal/builtin/builtin_required_unless.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/util/gconv" 14 "github.com/wangyougui/gf/v2/util/gutil" 15 ) 16 17 // RuleRequiredUnless implements `required-unless` rule: 18 // Required unless all given field and its value are not equal. 19 // 20 // Format: required-unless:field,value,... 21 // Example: required-unless:id,1,age,18 22 type RuleRequiredUnless struct{} 23 24 func init() { 25 Register(RuleRequiredUnless{}) 26 } 27 28 func (r RuleRequiredUnless) Name() string { 29 return "required-unless" 30 } 31 32 func (r RuleRequiredUnless) Message() string { 33 return "The {field} field is required" 34 } 35 36 func (r RuleRequiredUnless) Run(in RunInput) error { 37 var ( 38 required = true 39 array = strings.Split(in.RulePattern, ",") 40 foundValue interface{} 41 ) 42 // It supports multiple field and value pairs. 43 if len(array)%2 == 0 { 44 for i := 0; i < len(array); { 45 tk := array[i] 46 tv := array[i+1] 47 _, foundValue = gutil.MapPossibleItemByKey(in.Data.Map(), tk) 48 if in.Option.CaseInsensitive { 49 required = !strings.EqualFold(tv, gconv.String(foundValue)) 50 } else { 51 required = strings.Compare(tv, gconv.String(foundValue)) != 0 52 } 53 if !required { 54 break 55 } 56 i += 2 57 } 58 } 59 60 if required && isRequiredEmpty(in.Value.Val()) { 61 return errors.New(in.Message) 62 } 63 return nil 64 }