multipleof.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package validation
  2. import (
  3. "errors"
  4. "fmt"
  5. "reflect"
  6. )
  7. func MultipleOf(threshold interface{}) *multipleOfRule {
  8. return &multipleOfRule{
  9. threshold,
  10. fmt.Sprintf("must be multiple of %v", threshold),
  11. }
  12. }
  13. type multipleOfRule struct {
  14. threshold interface{}
  15. message string
  16. }
  17. // Error sets the error message for the rule.
  18. func (r *multipleOfRule) Error(message string) *multipleOfRule {
  19. r.message = message
  20. return r
  21. }
  22. func (r *multipleOfRule) Validate(value interface{}) error {
  23. rv := reflect.ValueOf(r.threshold)
  24. switch rv.Kind() {
  25. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  26. v, err := ToInt(value)
  27. if err != nil {
  28. return err
  29. }
  30. if v%rv.Int() == 0 {
  31. return nil
  32. }
  33. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  34. v, err := ToUint(value)
  35. if err != nil {
  36. return err
  37. }
  38. if v%rv.Uint() == 0 {
  39. return nil
  40. }
  41. default:
  42. return fmt.Errorf("type not supported: %v", rv.Type())
  43. }
  44. return errors.New(r.message)
  45. }