helper/validation: Add ValidateRegexp

This adds a ValidateRegexp validation helper to check to see if a field
has a valid regular expression.

Includes test for good regexp, and test for bad regexp.
This commit is contained in:
Chris Marchesi 2017-08-26 10:07:10 -07:00
parent 46bc77ff9a
commit afeeecd10d
No known key found for this signature in database
GPG Key ID: 335B84AFEC615CE4
2 changed files with 26 additions and 0 deletions

View File

@ -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
}

View File

@ -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