Skip to content

Commit

Permalink
Merge pull request #16774 from hashicorp/f-validation-stringmatch
Browse files Browse the repository at this point in the history
helper/validation: Add StringMatch
  • Loading branch information
vancluever authored Dec 5, 2017
2 parents 0891bd2 5da62a4 commit 8e57c43
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
21 changes: 21 additions & 0 deletions helper/validation/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 106,27 @@ func StringLenBetween(min, max int) schema.SchemaValidateFunc {
}
}

// StringMatch returns a SchemaValidateFunc which tests if the provided value
// matches a given regexp. Optionally an error message can be provided to
// return something friendlier than "must match some globby regexp".
func StringMatch(r *regexp.Regexp, message string) schema.SchemaValidateFunc {
return func(i interface{}, k string) ([]string, []error) {
v, ok := i.(string)
if !ok {
return nil, []error{fmt.Errorf("expected type of %s to be string", k)}
}

if ok := r.MatchString(v); !ok {
if message != "" {
return nil, []error{fmt.Errorf("invalid value for %s (%s)", k, message)}

}
return nil, []error{fmt.Errorf("expected value of %s to match regular expression %q", k, r)}
}
return nil, nil
}
}

// NoZeroValues is a SchemaValidateFunc which tests if the provided value is
// not a zero value. It's useful in situations where you want to catch
// explicit zero values on things like required fields during validation.
Expand Down
19 changes: 19 additions & 0 deletions helper/validation/validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 111,25 @@ func TestValidationStringInSlice(t *testing.T) {
})
}

func TestValidationStringMatch(t *testing.T) {
runTestCases(t, []testCase{
{
val: "foobar",
f: StringMatch(regexp.MustCompile(".*foo.*"), ""),
},
{
val: "bar",
f: StringMatch(regexp.MustCompile(".*foo.*"), ""),
expectedErr: regexp.MustCompile("expected value of [\\w] to match regular expression " regexp.QuoteMeta(`".*foo.*"`)),
},
{
val: "bar",
f: StringMatch(regexp.MustCompile(".*foo.*"), "value must contain foo"),
expectedErr: regexp.MustCompile("invalid value for [\\w] \\(value must contain foo\\)"),
},
})
}

func TestValidationRegexp(t *testing.T) {
runTestCases(t, []testCase{
{
Expand Down

0 comments on commit 8e57c43

Please sign in to comment.