rule_in.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package valid
  2. import "reflect"
  3. // ErrInInvalid is the error that returns in case of an invalid value for "in" rule.
  4. var ErrInInvalid = NewError("validation_in_invalid", "must be a valid value")
  5. // In returns a validation rule that checks if a value can be found in the given list of values.
  6. // reflect.DeepEqual() will be used to determine if two values are equal.
  7. // For more details please refer to https://golang.org/pkg/reflect/#DeepEqual
  8. // An empty value is considered valid. Use the Required rule to make sure a value is not empty.
  9. func In(values ...interface{}) InRule {
  10. return InRule{
  11. elements: values,
  12. err: ErrInInvalid,
  13. }
  14. }
  15. // InRule is a validation rule that validates if a value can be found in the given list of values.
  16. type InRule struct {
  17. elements []interface{}
  18. err Error
  19. }
  20. // Validate checks if the given value is valid or not.
  21. func (r InRule) Validate(value interface{}) error {
  22. value, isNil := Indirect(value)
  23. if isNil || IsEmpty(value) {
  24. return nil
  25. }
  26. for _, e := range r.elements {
  27. if reflect.DeepEqual(e, value) {
  28. return nil
  29. }
  30. }
  31. return r.err
  32. }
  33. // Error sets the error message for the rule.
  34. func (r InRule) Error(message string) InRule {
  35. r.err = r.err.SetMessage(message)
  36. return r
  37. }
  38. // ErrorObject sets the error struct for the rule.
  39. func (r InRule) ErrorObject(err Error) InRule {
  40. r.err = err
  41. return r
  42. }