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