1 package validation
2 3 import (
4 "fmt"
5 "reflect"
6 )
7 8 // ErrMultipleOfInvalid is the error that returns when a value is not multiple of a base.
9 var ErrMultipleOfInvalid = NewError("validation_multiple_of_invalid", "must be multiple of {{.base}}")
10 11 // MultipleOf returns a validation rule that checks if a value is a multiple of the "base" value.
12 // Note that "base" should be of integer type.
13 func MultipleOf(base interface{}) MultipleOfRule {
14 return MultipleOfRule{
15 base: base,
16 err: ErrMultipleOfInvalid,
17 }
18 }
19 20 // MultipleOfRule is a validation rule that checks if a value is a multiple of the "base" value.
21 type MultipleOfRule struct {
22 base interface{}
23 err Error
24 }
25 26 // Error sets the error message for the rule.
27 func (r MultipleOfRule) Error(message string) MultipleOfRule {
28 r.err = r.err.SetMessage(message)
29 return r
30 }
31 32 // ErrorObject sets the error struct for the rule.
33 func (r MultipleOfRule) ErrorObject(err Error) MultipleOfRule {
34 r.err = err
35 return r
36 }
37 38 // Validate checks if the value is a multiple of the "base" value.
39 func (r MultipleOfRule) Validate(value interface{}) error {
40 rv := reflect.ValueOf(r.base)
41 switch rv.Kind() {
42 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
43 v, err := ToInt(value)
44 if err != nil {
45 return err
46 }
47 if v%rv.Int() == 0 {
48 return nil
49 }
50 51 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
52 v, err := ToUint(value)
53 if err != nil {
54 return err
55 }
56 57 if v%rv.Uint() == 0 {
58 return nil
59 }
60 default:
61 return fmt.Errorf("type not supported: %v", rv.Type())
62 }
63 64 return r.err.SetParams(map[string]interface{}{"base": r.base})
65 }
66