rule_absent.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package valid
  2. var (
  3. // ErrNil is the error that returns when a value is not nil.
  4. ErrNil = NewError("validation_nil", "must be blank")
  5. // ErrEmpty is the error that returns when a not nil value is not empty.
  6. ErrEmpty = NewError("validation_empty", "must be blank")
  7. )
  8. // Nil is a validation rule that checks if a value is nil.
  9. // It is the opposite of NotNil rule
  10. var Nil = absentRule{condition: true, skipNil: false}
  11. // Empty checks if a not nil value is empty.
  12. var Empty = absentRule{condition: true, skipNil: true}
  13. type absentRule struct {
  14. condition bool
  15. err Error
  16. skipNil bool
  17. }
  18. // Validate checks if the given value is valid or not.
  19. func (r absentRule) Validate(value interface{}) error {
  20. if r.condition {
  21. value, isNil := Indirect(value)
  22. if !r.skipNil && !isNil || r.skipNil && !isNil && !IsEmpty(value) {
  23. if r.err != nil {
  24. return r.err
  25. }
  26. if r.skipNil {
  27. return ErrEmpty
  28. }
  29. return ErrNil
  30. }
  31. }
  32. return nil
  33. }
  34. // When sets the condition that determines if the validation should be performed.
  35. func (r absentRule) When(condition bool) absentRule {
  36. r.condition = condition
  37. return r
  38. }
  39. // Error sets the error message for the rule.
  40. func (r absentRule) Error(message string) absentRule {
  41. if r.err == nil {
  42. if r.skipNil {
  43. r.err = ErrEmpty
  44. } else {
  45. r.err = ErrNil
  46. }
  47. }
  48. r.err = r.err.SetMessage(message)
  49. return r
  50. }
  51. // ErrorObject sets the error struct for the rule.
  52. func (r absentRule) ErrorObject(err Error) absentRule {
  53. r.err = err
  54. return r
  55. }