Skip to content

String Regular Expression Matching #10

@bflad

Description

@bflad

Terraform CLI and Framework Versions

Any Terraform CLI version; terraform-plugin-framework v0.8.0

Use Cases or Problem Statement

Provider developers should be able to generically validate types.String values successfully match a regular expression, using the Go standard library regular expression engine.

Proposal

Inside a stringvalidator package, create a new unexported type that satisfies the tfsdk.AttributeValidator interface:

var _ regexMatchesValidator = tfsdk.AttributeValidator

type regexMatchesValidator struct {
  // Practitioner friendly message (defaults to (regexp.Regexp).String())
  message string
  regex regexp.Regexp
}

func (v regexMatchesValidator) Description(ctx context.Context) string {/*...*/}
func (v regexMatchesValidator) MarkdownDescription(ctx context.Context) string {/*...*/}
func (v regexMatchesValidator) Validate(ctx context.Context, req tfsdk.ValidateAttributeRequest, resp *tfsdk.ValidateAttributeResponse) {/*...*/}

Then, create exported function that returns it:

func RegexMatches(regex regexp.Regexp, message string) AttributeValidator {/*...*/}

This would allow provider developers to declare attributes such as:

tfsdk.Attribute{
  // ... other fields ...
  Type: types.String,
  Validators: tfsdk.AttributeValidators{
    stringvalidator.RegexMatches(regexp.MustCompile(`^[a-z]+$`), "must contain only lowercase alphabetical characters"),
  },
},

Additional Information

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requesttype/stringtypes.String validators

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions