-
Notifications
You must be signed in to change notification settings - Fork 1
/
validator.go
39 lines (35 loc) · 838 Bytes
/
validator.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
package forms
import (
"errors"
"regexp"
)
type ValidatorFunc func(interface{}) error
func ReValidator(pattern string, errorMsg string) ValidatorFunc {
validRe := regexp.MustCompile(pattern)
return ValidatorFunc(func(value interface{}) error {
strValue, ok := value.(string)
// check type assertion
if !ok {
return errors.New("Invalid string value")
}
// check regular expression
if !validRe.MatchString(strValue) {
return errors.New(errorMsg)
}
return nil
})
}
func RangeValidator(min, max int, errorMsg string) ValidatorFunc {
return ValidatorFunc(func(value interface{}) error {
intValue, ok := value.(int)
// check type assertion
if !ok {
return errors.New("Invalid int value")
}
// check range
if intValue < min || intValue > max {
return errors.New(errorMsg)
}
return nil
})
}