in.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. // In returns a validation rule that checks if a value can be found in the given list of values.
  7. // Note that the value being checked and the possible range of values must be of the same type.
  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. message: "must be a valid value",
  13. }
  14. }
  15. type InRule struct {
  16. elements []interface{}
  17. message string
  18. }
  19. // Validate checks if the given value is valid or not.
  20. func (r *InRule) Validate(value interface{}) error {
  21. value, isNil := Indirect(value)
  22. if isNil || IsEmpty(value) {
  23. return nil
  24. }
  25. for _, e := range r.elements {
  26. if e == value {
  27. return nil
  28. }
  29. }
  30. return errors.New(r.message)
  31. }
  32. // Error sets the error message for the rule.
  33. func (r *InRule) Error(message string) *InRule {
  34. r.message = message
  35. return r
  36. }