1
0
mirror of https://github.com/astaxie/beego.git synced 2024-06-02 11:53:28 +00:00

Add custom validation function

This commit is contained in:
miraclesu 2016-01-07 22:42:04 +08:00
parent bef6bca397
commit 103ac3ee5b

View File

@ -56,6 +56,27 @@ func init() {
} }
} }
type CustomFunc func(v *Validation, obj interface{}, key string)
// Add a custom function to validation
// The name can not be:
// Clear
// HasErrors
// ErrorMap
// Error
// Check
// Valid
// NoMatch
// If the name is same with exists function, it will replace the origin valid function
func AddCustomFunc(name string, f CustomFunc) error {
if unFuncs[name] {
return fmt.Errorf("invalid function name: %s", name)
}
funcs[name] = reflect.ValueOf(f)
return nil
}
// ValidFunc Valid function type // ValidFunc Valid function type
type ValidFunc struct { type ValidFunc struct {
Name string Name string
@ -102,7 +123,6 @@ func getValidFuncs(f reflect.StructField) (vfs []ValidFunc, err error) {
return return
} }
if vfs, tag, err = getRegFuncs(tag, f.Name); err != nil { if vfs, tag, err = getRegFuncs(tag, f.Name); err != nil {
fmt.Printf("%+v\n", err)
return return
} }
fs := strings.Split(tag, ";") fs := strings.Split(tag, ";")
@ -214,7 +234,7 @@ func trim(name, key string, s []string) (ts []interface{}, err error) {
for i := 0; i < len(s); i++ { for i := 0; i < len(s); i++ {
var param interface{} var param interface{}
// skip *Validation and obj params // skip *Validation and obj params
if param, err = magic(fn.Type().In(i+2), strings.TrimSpace(s[i])); err != nil { if param, err = parseParam(fn.Type().In(i+2), strings.TrimSpace(s[i])); err != nil {
return return
} }
ts[i] = param ts[i] = param
@ -224,7 +244,7 @@ func trim(name, key string, s []string) (ts []interface{}, err error) {
} }
// modify the parameters's type to adapt the function input parameters' type // modify the parameters's type to adapt the function input parameters' type
func magic(t reflect.Type, s string) (i interface{}, err error) { func parseParam(t reflect.Type, s string) (i interface{}, err error) {
switch t.Kind() { switch t.Kind() {
case reflect.Int: case reflect.Int:
i, err = strconv.Atoi(s) i, err = strconv.Atoi(s)