github.com/gogf/gf/v2@v2.7.4/util/gvalid/internal/builtin/builtin_required_without.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  // RuleRequiredWithout implements `required-without` rule:
    18  // Required if any of given fields are empty.
    19  //
    20  // Format:  required-without:field1,field2,...
    21  // Example: required-without:id,name
    22  type RuleRequiredWithout struct{}
    23  
    24  func init() {
    25  	Register(RuleRequiredWithout{})
    26  }
    27  
    28  func (r RuleRequiredWithout) Name() string {
    29  	return "required-without"
    30  }
    31  
    32  func (r RuleRequiredWithout) Message() string {
    33  	return "The {field} field is required"
    34  }
    35  
    36  func (r RuleRequiredWithout) 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  }