1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-22 00:50:55 +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
type ValidFunc struct {
Name string
@ -102,7 +123,6 @@ func getValidFuncs(f reflect.StructField) (vfs []ValidFunc, err error) {
return
}
if vfs, tag, err = getRegFuncs(tag, f.Name); err != nil {
fmt.Printf("%+v\n", err)
return
}
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++ {
var param interface{}
// 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
}
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
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() {
case reflect.Int:
i, err = strconv.Atoi(s)