github.com/gogf/gf/v2@v2.7.4/util/gvalid/internal/builtin/builtin_required_if.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 // RuleRequiredIf implements `required-if` rule: 20 // Required if any of given field and its value are equal. 21 // 22 // Format: required-if:field,value,... 23 // Example: required-if:id,1,age,18 24 type RuleRequiredIf struct{} 25 26 func init() { 27 Register(RuleRequiredIf{}) 28 } 29 30 func (r RuleRequiredIf) Name() string { 31 return "required-if" 32 } 33 34 func (r RuleRequiredIf) Message() string { 35 return "The {field} field is required" 36 } 37 38 func (r RuleRequiredIf) Run(in RunInput) error { 39 var ( 40 required = false 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 // It supports multiple field and value pairs. 54 for i := 0; i < len(array); { 55 var ( 56 tk = array[i] 57 tv = array[i+1] 58 ) 59 _, foundValue = gutil.MapPossibleItemByKey(dataMap, tk) 60 if in.Option.CaseInsensitive { 61 required = strings.EqualFold(tv, gconv.String(foundValue)) 62 } else { 63 required = strings.Compare(tv, gconv.String(foundValue)) == 0 64 } 65 if required { 66 break 67 } 68 i += 2 69 } 70 if required && isRequiredEmpty(in.Value.Val()) { 71 return errors.New(in.Message) 72 } 73 return nil 74 }