This repository has been archived by the owner on Aug 10, 2023. It is now read-only.
generated from hashicorp/terraform-provider-scaffolding
/
validators.go
70 lines (60 loc) · 1.71 KB
/
validators.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package provider
import (
"context"
"fmt"
"regexp"
"strings"
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
"github.com/hashicorp/terraform-plugin-framework/types"
)
type notEmptyString struct {
emptyDescriptions
}
func (notEmptyString) Validate(_ context.Context, req tfsdk.ValidateAttributeRequest, resp *tfsdk.ValidateAttributeResponse) {
attr := req.AttributeConfig.(types.String)
if attr.Unknown {
return
}
if attr.Value == "" {
resp.Diagnostics.AddAttributeError(req.AttributePath, "Empty String", "")
}
}
var emailRegex = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
func isEmailValid(e string) bool {
if len(e) < 3 && len(e) > 254 {
return false
}
return emailRegex.MatchString(e)
}
type email struct {
emptyDescriptions
}
func (email) Validate(_ context.Context, req tfsdk.ValidateAttributeRequest, resp *tfsdk.ValidateAttributeResponse) {
attr := req.AttributeConfig.(types.String)
if attr.Unknown {
return
}
if !isEmailValid(attr.Value) {
resp.Diagnostics.AddAttributeError(req.AttributePath, "Invalid email address", "")
}
}
type stringInSlice struct {
slice []string
optional bool
emptyDescriptions
}
func (s stringInSlice) Validate(_ context.Context, req tfsdk.ValidateAttributeRequest, resp *tfsdk.ValidateAttributeResponse) {
attr := req.AttributeConfig.(types.String)
if attr.Unknown {
return
}
if s.optional && attr.Null {
return
}
for _, item := range s.slice {
if attr.Value == item {
return
}
}
resp.Diagnostics.AddAttributeError(req.AttributePath, "Invalid string", fmt.Sprintf("String must be one of: [%s]", strings.Join(s.slice, ", ")))
}