diff --git a/helper/validation/validation.go b/helper/validation/validation.go index 01e131047..8c8ac54fc 100644 --- a/helper/validation/validation.go +++ b/helper/validation/validation.go @@ -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 { diff --git a/helper/validation/validation_test.go b/helper/validation/validation_test.go index b3f779c0a..26205d905 100644 --- a/helper/validation/validation_test.go +++ b/helper/validation/validation_test.go @@ -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{ {