diff --git a/helper/validation/validation.go b/helper/validation/validation.go index 221433b7cb..bb5dd2096a 100644 --- a/helper/validation/validation.go +++ b/helper/validation/validation.go @@ -3,6 +3,7 @@ package validation import ( "fmt" "net" + "regexp" "strings" "github.com/hashicorp/terraform/helper/schema" @@ -138,9 +139,20 @@ func CIDRNetwork(min, max int) schema.SchemaValidateFunc { } } +// ValidateJsonString is a SchemaValidateFunc which tests to make sure the +// supplied string is valid JSON. func ValidateJsonString(v interface{}, k string) (ws []string, errors []error) { if _, err := structure.NormalizeJsonString(v); err != nil { errors = append(errors, fmt.Errorf("%q contains an invalid JSON: %s", k, err)) } return } + +// ValidateRegexp returns a SchemaValidateFunc which tests to make sure the +// supplied string is a valid regular expression. +func ValidateRegexp(v interface{}, k string) (ws []string, errors []error) { + if _, err := regexp.Compile(v.(string)); err != nil { + errors = append(errors, fmt.Errorf("%q: %s", k, err)) + } + return +} diff --git a/helper/validation/validation_test.go b/helper/validation/validation_test.go index 0ca847fe62..ee2494f642 100644 --- a/helper/validation/validation_test.go +++ b/helper/validation/validation_test.go @@ -111,6 +111,20 @@ func TestValidationStringInSlice(t *testing.T) { }) } +func TestValidationRegexp(t *testing.T) { + runTestCases(t, []testCase{ + { + val: ".*foo.*", + f: ValidateRegexp, + }, + { + val: "foo(bar", + f: ValidateRegexp, + expectedErr: regexp.MustCompile(regexp.QuoteMeta("error parsing regexp: missing closing ): `foo(bar`")), + }, + }) +} + func TestValidateJsonString(t *testing.T) { type testCases struct { Value string