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:
parent
9434591652
commit
46804080aa
|
@ -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 {
|
||||
|
|
|
@ -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{
|
||||
{
|
||||
|
|
Loading…
Reference in New Issue