rule_when.go 1.3 KB

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