Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add RegexNotMatches validator #67

Merged
merged 1 commit into from
Jun 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
## 1.25.5 (June 18, 2024)

IMPROVEMENTS:

* Add `RegexNotMatches` Plugin Framework validator

## 1.25.4 (June 4, 2024)

IMPROVEMENTS:
Expand Down
61 changes: 61 additions & 0 deletions validator/fw/string/regex_not_match.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package string

import (
"context"
"fmt"
"regexp"

"github.com/hashicorp/terraform-plugin-framework-validators/helpers/validatordiag"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
)

// Ensure our implementation satisfies the validator.String interface.
var _ validator.String = &regexNotMatchesValidator{}

type regexNotMatchesValidator struct {
regexp *regexp.Regexp
message string
}

func (v regexNotMatchesValidator) Description(_ context.Context) string {
if v.message != "" {
return v.message
}
return fmt.Sprintf("value must not match regular expression '%s'", v.regexp)
}

func (v regexNotMatchesValidator) MarkdownDescription(ctx context.Context) string {
return v.Description(ctx)
}

func (v regexNotMatchesValidator) ValidateString(ctx context.Context, request validator.StringRequest, response *validator.StringResponse) {
if request.ConfigValue.IsNull() || request.ConfigValue.IsUnknown() {
return
}

value := request.ConfigValue.ValueString()

if v.regexp.MatchString(value) {
response.Diagnostics.Append(validatordiag.InvalidAttributeValueMatchDiagnostic(
request.Path,
v.Description(ctx),
value,
))
}
}

// RegexNotMatches returns an AttributeValidator which ensures that any configured
// attribute value:
//
// - Is a string.
// - Not matches the given regular expression https://github.com/google/re2/wiki/Syntax.
//
// Null (unconfigured) and unknown (known after apply) values are skipped.
// Optionally an error message can be provided to return something friendlier
// than "value must not match regular expression 'regexp'".
func RegexNotMatches(regexp *regexp.Regexp, message string) validator.String {
return regexNotMatchesValidator{
regexp: regexp,
message: message,
}
}
Loading