-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathcustom.go
45 lines (40 loc) · 926 Bytes
/
custom.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
package checker
import (
"fmt"
"reflect"
)
type customRule struct {
baseRule
checkFn func(exprValue interface{}) (bool, string)
}
func (r *customRule) Prompt(prompt string) Rule {
r.prompt = prompt
return r
}
func (r *customRule) Check(param interface{}) (bool, string) {
exprValue, kind := fetchField(param, r)
if kind == reflect.Invalid {
return false,
fmt.Sprintf("[%s]:%s cannot be found", r.name, r.getCompleteFieldExpr())
}
if exprValue == nil {
return false,
fmt.Sprintf("[%s]:%s is nil", r.name, r.getCompleteFieldExpr())
}
isValid, errMsg := r.checkFn(exprValue)
if !isValid {
return false,
fmt.Sprintf("[%s]:%s %s",
r.name, r.getCompleteFieldExpr(), errMsg)
}
return true, ""
}
func Custom(fieldExpr string, checkFn func(exprValue interface{}) (bool, string)) *customRule {
return &customRule{
baseRule{
fieldExpr: fieldExpr,
name: "Custom",
},
checkFn,
}
}