-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom.go
More file actions
60 lines (49 loc) · 1.27 KB
/
custom.go
File metadata and controls
60 lines (49 loc) · 1.27 KB
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
package validator_ext
import (
"errors"
"github.com/go-playground/validator/v10"
)
var customAliasMap = map[string]string{
IsCurrency: "iso4217",
IsCountry: "iso3166_1_alpha2|iso3166_1_alpha3|iso3166_1_alpha_numeric|" + ExtCountryCode,
}
var customValidatorMap = map[string]validator.Func{
MaxLength: maxLength,
MinLength: minLength,
IsDate: isDate,
IsDatetime: isDateTime,
Regex: regex,
IsMobile: isMobile,
MustIn: mustIn,
ExtCountryCode: extCountryCode,
}
var CustomValidator *validator.Validate
func NewCustomValidator() *validator.Validate {
if CustomValidator != nil {
return CustomValidator
}
CustomValidator = validator.New(validator.WithRequiredStructEnabled())
CustomValidator.SetTagName("binding")
AddCustomRules(CustomValidator)
return CustomValidator
}
func AddCustomRules(validate *validator.Validate) {
for k, v := range customAliasMap {
validate.RegisterAlias(k, v)
}
for k, v := range customValidatorMap {
err := validate.RegisterValidation(k, v)
if err != nil {
panic(err)
}
}
RegisterTranslations(validate)
}
func ValidateDefault(obj any) error {
err := CustomValidator.Struct(obj)
errMsg := TranslateValidateError(err, "")
if errMsg != "" {
return errors.New(errMsg)
}
return nil
}