Add validation CustomFunction example
This commit is contained in:
parent
d82475935d
commit
0f78ddc53a
@ -15,6 +15,7 @@
|
||||
package validation
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"reflect"
|
||||
"testing"
|
||||
@ -126,3 +127,29 @@ func TestCall(t *testing.T) {
|
||||
t.Error("age out of range should be has an error")
|
||||
}
|
||||
}
|
||||
|
||||
func ExampleAddCustomFunc() {
|
||||
err := AddCustomFunc("MyFunc", func(v *Validation, obj interface{}, key string) {
|
||||
// do validation, and if you find something wrong,
|
||||
// call AddError
|
||||
v.AddError(key, "this is my error")
|
||||
})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
type MyUser struct {
|
||||
Name string `valid:"MyFunc"`
|
||||
}
|
||||
v := Validation{}
|
||||
ok, err := v.Valid(&MyUser{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if !ok {
|
||||
// get the validation error here
|
||||
errs := v.Errors
|
||||
fmt.Println(errs[0].Error())
|
||||
}
|
||||
// Output:
|
||||
// Name this is my error
|
||||
}
|
||||
|
||||
@ -308,7 +308,7 @@ func (v *Validation) apply(chk Validator, obj interface{}) *Result {
|
||||
}
|
||||
}
|
||||
|
||||
// key must like aa.bb.cc or aa.bb.
|
||||
// AddError key must like aa.bb.cc or aa.bb.
|
||||
// AddError adds independent error message for the provided key
|
||||
func (v *Validation) AddError(key, message string) {
|
||||
Name := key
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user