Skip to content

Commit

Permalink
Merge pull request #67 from jfrog/add-regex-not-match-validtor
Browse files Browse the repository at this point in the history
Add RegexNotMatches validator
  • Loading branch information
alexhung authored Jun 18, 2024
2 parents f74b707 + 0a552f3 commit 75a7ea9
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
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,
}
}

0 comments on commit 75a7ea9

Please sign in to comment.