mirror of
https://github.com/opentofu/opentofu.git
synced 2024-12-28 01:41:48 -06:00
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:
parent
46bc77ff9a
commit
afeeecd10d
@ -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
|
||||
}
|
||||
|
@ -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
|
||||
|
Loading…
Reference in New Issue
Block a user