-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator.go
39 lines (31 loc) · 906 Bytes
/
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
package server
import (
"regexp"
"strings"
"github.com/go-playground/validator/v10"
)
// CustomValidator holds custom validator
type CustomValidator struct {
V *validator.Validate
}
// NewValidator creates new custom validator
func NewValidator() *CustomValidator {
V := validator.New()
V.RegisterValidation("date", validateDate)
V.RegisterValidation("phone", validatePhone)
return &CustomValidator{V}
}
// Validate validates the request
func (cv *CustomValidator) Validate(i interface{}) error {
return cv.V.Struct(i)
}
func validateDate(fl validator.FieldLevel) bool {
val := fl.Field().String()
re := regexp.MustCompile(`^\d{4}-\d{1,2}-\d{1,2}(T00:00:00Z)?$`)
return re.MatchString(val)
}
func validatePhone(fl validator.FieldLevel) bool {
val := fl.Field().String()
re := regexp.MustCompile(`^(\+\d{1,3})?\s?\d{5,15}$`)
return re.MatchString(strings.Replace(val, " ", "", -1))
}