-
Notifications
You must be signed in to change notification settings - Fork 167
/
cidr_validator.go
50 lines (41 loc) · 1.23 KB
/
cidr_validator.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
package validate
import (
"context"
"net"
"github.com/hashicorp/terraform-plugin-framework-validators/helpers/validatordiag"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
)
type CIDRValidator struct{}
func (v CIDRValidator) Description(_ context.Context) string {
return "string value must be defined as a valid cidr."
}
func (v CIDRValidator) MarkdownDescription(ctx context.Context) string {
return v.Description(ctx)
}
func (v CIDRValidator) ValidateString(ctx context.Context, req validator.StringRequest, response *validator.StringResponse) {
// If the value is unknown or null, there is nothing to validate.
if req.ConfigValue.IsUnknown() || req.ConfigValue.IsNull() {
return
}
value := req.ConfigValue.ValueString()
_, ipnet, err := net.ParseCIDR(value)
if err != nil {
response.Diagnostics.Append(validatordiag.InvalidAttributeValueDiagnostic(
req.Path,
v.Description(ctx),
req.ConfigValue.ValueString(),
))
return
}
if ipnet == nil || ipnet.String() != value {
response.Diagnostics.Append(validatordiag.InvalidAttributeValueDiagnostic(
req.Path,
v.Description(ctx),
req.ConfigValue.ValueString(),
))
return
}
}
func ValidCIDR() validator.String {
return CIDRValidator{}
}