Add validation CustomFunction example

This commit is contained in:
Deng Ming 2024-09-02 14:05:39 +08:00 committed by Ming Deng
parent d82475935d
commit 0f78ddc53a
2 changed files with 28 additions and 1 deletions

View File

@ -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
}

View File

@ -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