forked from ebhomengo/niki
1
0
Fork 0
niki/vendor/github.com/go-ozzo/ozzo-validation/v4/multipleof.go

104 lines
1.7 KiB
Go
Raw Normal View History

2024-02-18 10:42:21 +00:00
package validation
import (
"fmt"
"reflect"
)
// ErrMultipleOfInvalid is the error that returns when a value is not multiple of a base.
2024-02-18 10:42:21 +00:00
var ErrMultipleOfInvalid = NewError("validation_multiple_of_invalid", "must be multiple of {{.base}}")
// MultipleOf returns a validation rule that checks if a value is a multiple of the "base" value.
2024-02-18 10:42:21 +00:00
// Note that "base" should be of integer type.
2024-02-18 10:42:21 +00:00
func MultipleOf(base interface{}) MultipleOfRule {
2024-02-18 10:42:21 +00:00
return MultipleOfRule{
2024-02-18 10:42:21 +00:00
base: base,
err: ErrMultipleOfInvalid,
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// MultipleOfRule is a validation rule that checks if a value is a multiple of the "base" value.
2024-02-18 10:42:21 +00:00
type MultipleOfRule struct {
base interface{}
err Error
2024-02-18 10:42:21 +00:00
}
// Error sets the error message for the rule.
2024-02-18 10:42:21 +00:00
func (r MultipleOfRule) Error(message string) MultipleOfRule {
2024-02-18 10:42:21 +00:00
r.err = r.err.SetMessage(message)
2024-02-18 10:42:21 +00:00
return r
2024-02-18 10:42:21 +00:00
}
// ErrorObject sets the error struct for the rule.
2024-02-18 10:42:21 +00:00
func (r MultipleOfRule) ErrorObject(err Error) MultipleOfRule {
2024-02-18 10:42:21 +00:00
r.err = err
2024-02-18 10:42:21 +00:00
return r
2024-02-18 10:42:21 +00:00
}
// Validate checks if the value is a multiple of the "base" value.
2024-02-18 10:42:21 +00:00
func (r MultipleOfRule) Validate(value interface{}) error {
2024-02-18 10:42:21 +00:00
rv := reflect.ValueOf(r.base)
2024-02-18 10:42:21 +00:00
switch rv.Kind() {
2024-02-18 10:42:21 +00:00
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
2024-02-18 10:42:21 +00:00
v, err := ToInt(value)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if v%rv.Int() == 0 {
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
2024-02-18 10:42:21 +00:00
v, err := ToUint(value)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
if v%rv.Uint() == 0 {
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
return fmt.Errorf("type not supported: %v", rv.Type())
2024-02-18 10:42:21 +00:00
}
return r.err.SetParams(map[string]interface{}{"base": r.base})
2024-02-18 10:42:21 +00:00
}