not_nil.go 819 B

123456789101112131415161718192021222324252627282930313233
  1. // Copyright 2016 Qiang Xue. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package validation
  5. import "errors"
  6. // NotNil is a validation rule that checks if a value is not nil.
  7. // NotNil only handles types including interface, pointer, slice, and map.
  8. // All other types are considered valid.
  9. var NotNil = &notNilRule{message: "is required"}
  10. type notNilRule struct {
  11. message string
  12. }
  13. // Validate checks if the given value is valid or not.
  14. func (r *notNilRule) Validate(value interface{}) error {
  15. _, isNil := Indirect(value)
  16. if isNil {
  17. return errors.New(r.message)
  18. }
  19. return nil
  20. }
  21. // Error sets the error message for the rule.
  22. func (r *notNilRule) Error(message string) *notNilRule {
  23. return &notNilRule{
  24. message: message,
  25. }
  26. }