github.com/gogf/gf/v2@v2.7.4/util/gvalid/internal/builtin/builtin_required_unless.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/util/gconv"
    14  	"github.com/gogf/gf/v2/util/gutil"
    15  )
    16  
    17  // RuleRequiredUnless implements `required-unless` rule:
    18  // Required unless all given field and its value are not equal.
    19  //
    20  // Format:  required-unless:field,value,...
    21  // Example: required-unless:id,1,age,18
    22  type RuleRequiredUnless struct{}
    23  
    24  func init() {
    25  	Register(RuleRequiredUnless{})
    26  }
    27  
    28  func (r RuleRequiredUnless) Name() string {
    29  	return "required-unless"
    30  }
    31  
    32  func (r RuleRequiredUnless) Message() string {
    33  	return "The {field} field is required"
    34  }
    35  
    36  func (r RuleRequiredUnless) 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  	// It supports multiple field and value pairs.
    45  	if len(array)%2 == 0 {
    46  		for i := 0; i < len(array); {
    47  			tk := array[i]
    48  			tv := array[i+1]
    49  			_, foundValue = gutil.MapPossibleItemByKey(dataMap, tk)
    50  			if in.Option.CaseInsensitive {
    51  				required = !strings.EqualFold(tv, gconv.String(foundValue))
    52  			} else {
    53  				required = strings.Compare(tv, gconv.String(foundValue)) != 0
    54  			}
    55  			if !required {
    56  				break
    57  			}
    58  			i += 2
    59  		}
    60  	}
    61  
    62  	if required && isRequiredEmpty(in.Value.Val()) {
    63  		return errors.New(in.Message)
    64  	}
    65  	return nil
    66  }