Commit 103ac3ee authored by miraclesu's avatar miraclesu

Add custom validation function

parent bef6bca3
...@@ -56,6 +56,27 @@ func init() { ...@@ -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) { ...@@ -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) { ...@@ -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) { ...@@ -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)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment