github.com/gogf/gf/v2@v2.7.4/util/gvalid/internal/builtin/builtin_required_without_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/internal/empty" 14 "github.com/gogf/gf/v2/util/gutil" 15 ) 16 17 // RuleRequiredWithoutAll implements `required-without-all` rule: 18 // Required if all given fields are empty. 19 // 20 // Format: required-without-all:field1,field2,... 21 // Example: required-without-all:id,name 22 type RuleRequiredWithoutAll struct{} 23 24 func init() { 25 Register(RuleRequiredWithoutAll{}) 26 } 27 28 func (r RuleRequiredWithoutAll) Name() string { 29 return "required-without-all" 30 } 31 32 func (r RuleRequiredWithoutAll) Message() string { 33 return "The {field} field is required" 34 } 35 36 func (r RuleRequiredWithoutAll) Run(in RunInput) error { 37 var ( 38 required = true 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 = false 48 break 49 } 50 } 51 52 if required && isRequiredEmpty(in.Value.Val()) { 53 return errors.New(in.Message) 54 } 55 return nil 56 }