rule_not_in.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package valid
  2. // ErrNotInInvalid is the error that returns when a value is in a list.
  3. var ErrNotInInvalid = NewError("validation_not_in_invalid", "must not be in list")
  4. // NotIn returns a validation rule that checks if a value is absent from the given list of values.
  5. // Note that the value being checked and the possible range of values must be of the same type.
  6. // An empty value is considered valid. Use the Required rule to make sure a value is not empty.
  7. func NotIn(values ...interface{}) NotInRule {
  8. return NotInRule{
  9. elements: values,
  10. err: ErrNotInInvalid,
  11. }
  12. }
  13. // NotInRule is a validation rule that checks if a value is absent from the given list of values.
  14. type NotInRule struct {
  15. elements []interface{}
  16. err Error
  17. }
  18. // Validate checks if the given value is valid or not.
  19. func (r NotInRule) Validate(value interface{}) error {
  20. value, isNil := Indirect(value)
  21. if isNil || IsEmpty(value) {
  22. return nil
  23. }
  24. for _, e := range r.elements {
  25. if e == value {
  26. return r.err
  27. }
  28. }
  29. return nil
  30. }
  31. // Error sets the error message for the rule.
  32. func (r NotInRule) Error(message string) NotInRule {
  33. r.err = r.err.SetMessage(message)
  34. return r
  35. }
  36. // ErrorObject sets the error struct for the rule.
  37. func (r NotInRule) ErrorObject(err Error) NotInRule {
  38. r.err = err
  39. return r
  40. }