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