when.go raw

   1  package validation
   2  
   3  import "context"
   4  
   5  // When returns a validation rule that executes the given list of rules when the condition is true.
   6  func When(condition bool, rules ...Rule) WhenRule {
   7  	return WhenRule{
   8  		condition: condition,
   9  		rules:     rules,
  10  		elseRules: []Rule{},
  11  	}
  12  }
  13  
  14  // WhenRule is a validation rule that executes the given list of rules when the condition is true.
  15  type WhenRule struct {
  16  	condition bool
  17  	rules     []Rule
  18  	elseRules []Rule
  19  }
  20  
  21  // Validate checks if the condition is true and if so, it validates the value using the specified rules.
  22  func (r WhenRule) Validate(value interface{}) error {
  23  	return r.ValidateWithContext(nil, value)
  24  }
  25  
  26  // ValidateWithContext checks if the condition is true and if so, it validates the value using the specified rules.
  27  func (r WhenRule) ValidateWithContext(ctx context.Context, value interface{}) error {
  28  	if r.condition {
  29  		if ctx == nil {
  30  			return Validate(value, r.rules...)
  31  		} else {
  32  			return ValidateWithContext(ctx, value, r.rules...)
  33  		}
  34  	}
  35  
  36  	if ctx == nil {
  37  		return Validate(value, r.elseRules...)
  38  	} else {
  39  		return ValidateWithContext(ctx, value, r.elseRules...)
  40  	}
  41  }
  42  
  43  // Else returns a validation rule that executes the given list of rules when the condition is false.
  44  func (r WhenRule) Else(rules ...Rule) WhenRule {
  45  	r.elseRules = rules
  46  	return r
  47  }
  48