helper/validation: Add Any() SchemaValidateFunc

`Any()` allows any single passing validation of multiple `SchemaValidateFunc` to pass validation to cover cases where a standard validation function does not cover the functionality or to make error messaging simpler.

Example provider usage:

```go
ValidateFunc: validation.Any(
  validation.IntAtLeast(42),
  validation.IntAtMost(5),
),
```
This commit is contained in:
Brian Flad 2018-10-18 20:58:53 -04:00
parent 9434591652
commit 46804080aa
No known key found for this signature in database
GPG Key ID: EC6252B42B012823
2 changed files with 53 additions and 0 deletions

View File

@ -28,6 +28,24 @@ func All(validators ...schema.SchemaValidateFunc) schema.SchemaValidateFunc {
}
}
// Any returns a SchemaValidateFunc which tests if the provided value
// passes any of the provided SchemaValidateFunc
func Any(validators ...schema.SchemaValidateFunc) schema.SchemaValidateFunc {
return func(i interface{}, k string) ([]string, []error) {
var allErrors []error
var allWarnings []string
for _, validator := range validators {
validatorWarnings, validatorErrors := validator(i, k)
if len(validatorWarnings) == 0 && len(validatorErrors) == 0 {
return []string{}, []error{}
}
allWarnings = append(allWarnings, validatorWarnings...)
allErrors = append(allErrors, validatorErrors...)
}
return allWarnings, allErrors
}
}
// IntBetween returns a SchemaValidateFunc which tests if the provided value
// is of type int and is between min and max (inclusive)
func IntBetween(min, max int) schema.SchemaValidateFunc {

View File

@ -41,6 +41,41 @@ func TestValidationAll(t *testing.T) {
})
}
func TestValidationAny(t *testing.T) {
runTestCases(t, []testCase{
{
val: 43,
f: Any(
IntAtLeast(42),
IntAtMost(5),
),
},
{
val: 4,
f: Any(
IntAtLeast(42),
IntAtMost(5),
),
},
{
val: 7,
f: Any(
IntAtLeast(42),
IntAtMost(5),
),
expectedErr: regexp.MustCompile("expected [\\w]+ to be at least \\(42\\), got 7"),
},
{
val: 7,
f: Any(
IntAtLeast(42),
IntAtMost(5),
),
expectedErr: regexp.MustCompile("expected [\\w]+ to be at most \\(5\\), got 7"),
},
})
}
func TestValidationIntBetween(t *testing.T) {
runTestCases(t, []testCase{
{