rule_not_nil.go 979 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package valid
  2. // ErrNotNilRequired is the error that returns when a value is Nil.
  3. var ErrNotNilRequired = NewError("validation_not_nil_required", "is required")
  4. // NotNil is a validation rule that checks if a value is not nil.
  5. // NotNil only handles types including interface, pointer, slice, and map.
  6. // All other types are considered valid.
  7. var NotNil = notNilRule{}
  8. type notNilRule struct {
  9. err Error
  10. }
  11. // Validate checks if the given value is valid or not.
  12. func (r notNilRule) Validate(value interface{}) error {
  13. _, isNil := Indirect(value)
  14. if isNil {
  15. if r.err != nil {
  16. return r.err
  17. }
  18. return ErrNotNilRequired
  19. }
  20. return nil
  21. }
  22. // Error sets the error message for the rule.
  23. func (r notNilRule) Error(message string) notNilRule {
  24. if r.err == nil {
  25. r.err = ErrNotNilRequired
  26. }
  27. r.err = r.err.SetMessage(message)
  28. return r
  29. }
  30. // ErrorObject sets the error struct for the rule.
  31. func (r notNilRule) ErrorObject(err Error) notNilRule {
  32. r.err = err
  33. return r
  34. }