github.com/wangyougui/gf/v2@v2.6.5/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/wangyougui/gf. 6 7 package builtin 8 9 import ( 10 "errors" 11 "strings" 12 13 "github.com/wangyougui/gf/v2/internal/empty" 14 "github.com/wangyougui/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 ) 42 for i := 0; i < len(array); i++ { 43 _, foundValue = gutil.MapPossibleItemByKey(in.Data.Map(), array[i]) 44 if !empty.IsEmpty(foundValue) { 45 required = false 46 break 47 } 48 } 49 50 if required && isRequiredEmpty(in.Value.Val()) { 51 return errors.New(in.Message) 52 } 53 return nil 54 }