Skip to content

Commit

Permalink
Fixes #64: added example of parameterizing custom rules
Browse files Browse the repository at this point in the history
  • Loading branch information
qiangxue committed Aug 7, 2019
1 parent 2882aa0 commit 199b55b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
14 changes: 14 additions & 0 deletions validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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) {
Expand Down

0 comments on commit 199b55b

Please sign in to comment.