not_in.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Copyright 2018 Qiang Xue, Google LLC. 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 (
  6. "errors"
  7. )
  8. // NotIn returns a validation rule that checks if a value os absent from, the given list of values.
  9. // Note that the value being checked and the possible range of values must be of the same type.
  10. // An empty value is considered valid. Use the Required rule to make sure a value is not empty.
  11. func NotIn(values ...interface{}) *NotInRule {
  12. return &NotInRule{
  13. elements: values,
  14. message: "must not be in list",
  15. }
  16. }
  17. type NotInRule struct {
  18. elements []interface{}
  19. message string
  20. }
  21. // Validate checks if the given value is valid or not.
  22. func (r *NotInRule) Validate(value interface{}) error {
  23. value, isNil := Indirect(value)
  24. if isNil || IsEmpty(value) {
  25. return nil
  26. }
  27. for _, e := range r.elements {
  28. if e == value {
  29. return errors.New(r.message)
  30. }
  31. }
  32. return nil
  33. }
  34. // Error sets the error message for the rule.
  35. func (r *NotInRule) Error(message string) *NotInRule {
  36. r.message = message
  37. return r
  38. }