github.com/gogf/gf/v2@v2.7.4/util/gvalid/internal/builtin/builtin_required_with.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/internal/empty" 14 "github.com/gogf/gf/v2/util/gutil" 15 ) 16 17 // RuleRequiredWith implements `required-with` rule: 18 // Required if any of given fields are not empty. 19 // 20 // Format: required-with:field1,field2,... 21 // Example: required-with:id,name 22 type RuleRequiredWith struct{} 23 24 func init() { 25 Register(RuleRequiredWith{}) 26 } 27 28 func (r RuleRequiredWith) Name() string { 29 return "required-with" 30 } 31 32 func (r RuleRequiredWith) Message() string { 33 return "The {field} field is required" 34 } 35 36 func (r RuleRequiredWith) Run(in RunInput) error { 37 var ( 38 required = false 39 array = strings.Split(in.RulePattern, ",") 40 foundValue interface{} 41 dataMap = in.Data.Map() 42 ) 43 44 for i := 0; i < len(array); i++ { 45 _, foundValue = gutil.MapPossibleItemByKey(dataMap, array[i]) 46 if !empty.IsEmpty(foundValue) { 47 required = true 48 break 49 } 50 } 51 52 if required && isRequiredEmpty(in.Value.Val()) { 53 return errors.New(in.Message) 54 } 55 return nil 56 }