diff --git a/helper/validation/validation.go b/helper/validation/validation.go index 7b894f540..221433b7c 100644 --- a/helper/validation/validation.go +++ b/helper/validation/validation.go @@ -28,6 +28,44 @@ func IntBetween(min, max int) schema.SchemaValidateFunc { } } +// IntAtLeast returns a SchemaValidateFunc which tests if the provided value +// is of type int and is at least min (inclusive) +func IntAtLeast(min int) schema.SchemaValidateFunc { + return func(i interface{}, k string) (s []string, es []error) { + v, ok := i.(int) + if !ok { + es = append(es, fmt.Errorf("expected type of %s to be int", k)) + return + } + + if v < min { + es = append(es, fmt.Errorf("expected %s to be at least (%d), got %d", k, min, v)) + return + } + + return + } +} + +// IntAtMost returns a SchemaValidateFunc which tests if the provided value +// is of type int and is at most max (inclusive) +func IntAtMost(max int) schema.SchemaValidateFunc { + return func(i interface{}, k string) (s []string, es []error) { + v, ok := i.(int) + if !ok { + es = append(es, fmt.Errorf("expected type of %s to be int", k)) + return + } + + if v > max { + es = append(es, fmt.Errorf("expected %s to be at most (%d), got %d", k, max, v)) + return + } + + return + } +} + // StringInSlice returns a SchemaValidateFunc which tests if the provided value // is of type string and matches the value of an element in the valid slice // will test with in lower case if ignoreCase is true diff --git a/helper/validation/validation_test.go b/helper/validation/validation_test.go index 991955d23..0ca847fe6 100644 --- a/helper/validation/validation_test.go +++ b/helper/validation/validation_test.go @@ -36,6 +36,52 @@ func TestValidationIntBetween(t *testing.T) { }) } +func TestValidationIntAtLeast(t *testing.T) { + runTestCases(t, []testCase{ + { + val: 1, + f: IntAtLeast(1), + }, + { + val: 1, + f: IntAtLeast(0), + }, + { + val: 1, + f: IntAtLeast(2), + expectedErr: regexp.MustCompile("expected [\\w]+ to be at least \\(2\\), got 1"), + }, + { + val: "1", + f: IntAtLeast(2), + expectedErr: regexp.MustCompile("expected type of [\\w]+ to be int"), + }, + }) +} + +func TestValidationIntAtMost(t *testing.T) { + runTestCases(t, []testCase{ + { + val: 1, + f: IntAtMost(1), + }, + { + val: 1, + f: IntAtMost(2), + }, + { + val: 1, + f: IntAtMost(0), + expectedErr: regexp.MustCompile("expected [\\w]+ to be at most \\(0\\), got 1"), + }, + { + val: "1", + f: IntAtMost(0), + expectedErr: regexp.MustCompile("expected type of [\\w]+ to be int"), + }, + }) +} + func TestValidationStringInSlice(t *testing.T) { runTestCases(t, []testCase{ {