From 0f78ddc53a38678764fef2b27beda2d81530aca2 Mon Sep 17 00:00:00 2001 From: Deng Ming Date: Mon, 2 Sep 2024 14:05:39 +0800 Subject: [PATCH] Add validation CustomFunction example --- core/validation/util_test.go | 27 +++++++++++++++++++++++++++ core/validation/validation.go | 2 +- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/core/validation/util_test.go b/core/validation/util_test.go index 58ca38db..d9227082 100644 --- a/core/validation/util_test.go +++ b/core/validation/util_test.go @@ -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 +} diff --git a/core/validation/validation.go b/core/validation/validation.go index bfb1dd92..b206520a 100644 --- a/core/validation/validation.go +++ b/core/validation/validation.go @@ -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