rule_required.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package valid
  2. var (
  3. // Required is a validation rule that checks if a value is not empty.
  4. // A value is considered not empty if
  5. // - integer, float: not zero
  6. // - bool: true
  7. // - string, array, slice, map: len() > 0
  8. // - interface, pointer: not nil and the referenced value is not empty
  9. // - any other types
  10. Required = RequiredRule{skipNil: false, condition: true}
  11. // NilOrNotEmpty checks if a value is a nil pointer or a value that is not empty.
  12. // NilOrNotEmpty differs from Required in that it treats a nil pointer as valid.
  13. NilOrNotEmpty = RequiredRule{skipNil: true, condition: true}
  14. // ErrRequired is the error that returns when a value is required.
  15. ErrRequired = NewError("validation_required", "cannot be blank")
  16. )
  17. // RequiredRule is a rule that checks if a value is not empty.
  18. type RequiredRule struct {
  19. condition bool
  20. skipNil bool
  21. err Error
  22. }
  23. // Validate checks if the given value is valid or not.
  24. func (r RequiredRule) Validate(value interface{}) error {
  25. if r.condition {
  26. value, isNil := Indirect(value)
  27. if r.skipNil && !isNil && IsEmpty(value) || !r.skipNil && (isNil || IsEmpty(value)) {
  28. if r.err != nil {
  29. return r.err
  30. }
  31. if r.skipNil {
  32. return ErrNilOrNotEmpty
  33. }
  34. return ErrRequired
  35. }
  36. }
  37. return nil
  38. }
  39. // When sets the condition that determines if the validation should be performed.
  40. func (r RequiredRule) When(condition bool) RequiredRule {
  41. r.condition = condition
  42. return r
  43. }
  44. // Error sets the error message for the rule.
  45. func (r RequiredRule) Error(message string) RequiredRule {
  46. if r.err == nil {
  47. if r.skipNil {
  48. r.err = ErrNilOrNotEmpty
  49. } else {
  50. r.err = ErrRequired
  51. }
  52. }
  53. r.err = r.err.SetMessage(message)
  54. return r
  55. }
  56. // ErrorObject sets the error struct for the rule.
  57. func (r RequiredRule) ErrorObject(err Error) RequiredRule {
  58. r.err = err
  59. return r
  60. }