/
validators.go
59 lines (50 loc) · 1.48 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
package configs
import (
"fmt"
"regexp"
"github.com/hashicorp/go-cty/cty"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
func StringMatchesRegexp(rs string) schema.SchemaValidateDiagFunc {
r, err := regexp.Compile(rs)
if err != nil {
panic(err)
}
return validation.ToDiagFunc(func(i interface{}, k string) ([]string, []error) {
v, ok := i.(string)
if !ok {
return nil, []error{fmt.Errorf("value for %q is not of type string", k)}
}
if ok := r.MatchString(v); !ok {
return nil, []error{fmt.Errorf("value for %q does not match regular expression %q", k, r)}
}
return nil, nil
})
}
func StringNotMatchesRegexp(rs string) schema.SchemaValidateDiagFunc {
r, err := regexp.Compile(rs)
if err != nil {
panic(err)
}
return validation.ToDiagFunc(func(i interface{}, k string) ([]string, []error) {
v, ok := i.(string)
if !ok {
return nil, []error{fmt.Errorf("value for %q is not of type string", k)}
}
if ok := r.MatchString(v); ok {
return nil, []error{fmt.Errorf("value for %q does matches regular expression %q", k, r)}
}
return nil, nil
})
}
func ValidateAll(validators ...schema.SchemaValidateDiagFunc) schema.SchemaValidateDiagFunc {
return func(i interface{}, p cty.Path) diag.Diagnostics {
var d diag.Diagnostics
for _, validator := range validators {
d = append(d, validator(i, p)...)
}
return d
}
}