-
Notifications
You must be signed in to change notification settings - Fork 117
/
validate.go
41 lines (32 loc) · 1.04 KB
/
validate.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
package database
import (
"regexp"
"github.com/go-playground/validator/v10"
)
// Validate validates a struct based on struct tags and other custom rules registered
func Validate(v any) error {
return validate.Struct(v)
}
// validate caches parsed validation rules
var validate *validator.Validate
// slugRegexp is used to validate identifying names (e.g. "rill-data", not "Rill Data").
var slugRegexp = regexp.MustCompile("^[_a-zA-Z0-9][-_a-zA-Z0-9]{2,39}$")
// Regular expression to match a domain name
var domainRegex = regexp.MustCompile(`^[a-zA-Z0-9]+([-.][a-zA-Z0-9]+)*\.[a-zA-Z]{2,}$`)
func init() {
validate = validator.New()
// Register "slug" validation rule
err := validate.RegisterValidation("slug", func(fl validator.FieldLevel) bool {
return slugRegexp.MatchString(fl.Field().String())
})
if err != nil {
panic(err)
}
// Register "domain" validation rule
err = validate.RegisterValidation("domain", func(fl validator.FieldLevel) bool {
return domainRegex.MatchString(fl.Field().String())
})
if err != nil {
panic(err)
}
}