forked from go-ozzo/ozzo-validation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
multipleof.go
55 lines (45 loc) · 1.01 KB
/
multipleof.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package validation
import (
"errors"
"fmt"
"reflect"
)
func MultipleOf(threshold interface{}) *multipleOfRule {
return &multipleOfRule{
threshold,
fmt.Sprintf("must be multiple of %v", threshold),
}
}
type multipleOfRule struct {
threshold interface{}
message string
}
// Error sets the error message for the rule.
func (r *multipleOfRule) Error(message string) *multipleOfRule {
r.message = message
return r
}
func (r *multipleOfRule) Validate(value interface{}) error {
rv := reflect.ValueOf(r.threshold)
switch rv.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
v, err := ToInt(value)
if err != nil {
return err
}
if v%rv.Int() == 0 {
return nil
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
v, err := ToUint(value)
if err != nil {
return err
}
if v%rv.Uint() == 0 {
return nil
}
default:
return fmt.Errorf("type not supported: %v", rv.Type())
}
return errors.New(r.message)
}