Skip to content

Commit

Permalink
added documentation about rule groups
Browse files Browse the repository at this point in the history
  • Loading branch information
Qiang Xue committed Feb 11, 2017
1 parent cb3f67a commit 6867c4e
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,7 @@ fmt.Println(err)
// must be a string with five digits
```


## Creating Custom Rules

Creating a custom rule is as simple as implementing the `validation.Rule` interface. The interface contains a single
Expand All @@ -370,6 +371,35 @@ method as shown below, which should validate the value and return the validation
Validate(value interface{}) error
```


### Rule Groups

When a combination of several rules are used in multiple places, you may use the following trick to create a
rule group so that your code is more maintainable.

```go
var NameRule = []validation.Rule{
validation.Required,
validation.Length(5, 20),
}

type User struct {
FirstName string
LastName string
}

func (u User) Validate() error {
return validation.ValidateStruct(&u,
validation.Field(&u.FirstName, NameRule...),
validation.Field(&u.LastName, NameRule...),
)
}
```

In the above example, we create a rule group `NameRule` which consists of two validation rules. We then use this rule
group to validate both `FirstName` and `LastName`.


## Credits

The `is` sub-package wraps the excellent validators provided by the [govalidator](https://github.com/asaskevich/govalidator) package.

0 comments on commit 6867c4e

Please sign in to comment.