Skip to content

Map Element Validation (KeysAre / ValuesAre) #13

@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 that every types.Map element key or value can be generically validated.

Proposal

Inside a mapvalidator package, create new unexported types that satisfies the tfsdk.AttributeValidator interface:

var _ keysAreValidator = tfsdk.AttributeValidator

type keysAreValidator struct {
  keyValidators []AttributeValidators
}

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

var _ valuesAreValidator = tfsdk.AttributeValidator

type valuesAreValidator struct {
  valueValidators []AttributeValidators
}

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

Then, create an exported function that returns it:

func KeysAre(keyValidators AttributeValidator...) AttributeValidator {/*...*/}
func ValuesAre(valueValidators AttributeValidator...) AttributeValidator {/*...*/}

This would allow provider developers to declare attributes such as:

tfsdk.Attribute{
  // ... other fields ...
  Type: types.Map{
    ElemType: types.String,
  },
  Validators: tfsdk.AttributeValidators{
    mapvalidator.KeysAre(
      stringvalidator.LengthBetween(1, 255),
      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

Labels

enhancementNew feature or requesttype/maptypes.Map validators

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions