From 199b55b36bc1af151e6eea487cc92ffa5b460b81 Mon Sep 17 00:00:00 2001 From: qiangxue Date: Wed, 7 Aug 2019 13:27:03 -0400 Subject: [PATCH] Fixes #64: added example of parameterizing custom rules --- README.md | 18 ++++++++++++++++++ validation_test.go | 14 ++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/README.md b/README.md index a666f96..2f74a1d 100644 --- a/README.md +++ b/README.md @@ -533,6 +533,24 @@ fmt.Println(err) // Output: must be abc ``` +If your validation function takes additional parameters, you can use the following closure trick: + +```go +func stringEquals(str string) validation.RuleFunc { + return func(value interface{}) error { + s, _ := value.(string) + if s != str { + return errors.New("unexpected string") + } + return nil + } +} + +err := validation.Validate("xyz", validation.By(stringEquals("abc"))) +fmt.Println(err) +// Output: unexpected string +``` + ### Rule Groups diff --git a/validation_test.go b/validation_test.go index 175bf7c..3bbd823 100644 --- a/validation_test.go +++ b/validation_test.go @@ -55,6 +55,16 @@ func TestValidate(t *testing.T) { assert.Nil(t, err) } +func stringEqual(str string) RuleFunc { + return func(value interface{}) error { + s, _ := value.(string) + if s != str { + return errors.New("unexpected string") + } + return nil + } +} + func TestBy(t *testing.T) { abcRule := By(func(value interface{}) error { s, _ := value.(string) @@ -68,6 +78,10 @@ func TestBy(t *testing.T) { if assert.NotNil(t, err) { assert.Equal(t, "must be abc", err.Error()) } + + xyzRule := By(stringEqual("xyz")) + assert.Nil(t, Validate("xyz", xyzRule)) + assert.NotNil(t, Validate("abc", xyzRule)) } func Test_skipRule_Validate(t *testing.T) {