-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformatter.go
More file actions
66 lines (55 loc) · 1.5 KB
/
formatter.go
File metadata and controls
66 lines (55 loc) · 1.5 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
61
62
63
64
65
66
package validatorerrors
import (
"fmt"
"github.com/go-playground/validator/v10"
)
type RuleFunc func(e validator.FieldError) string
type ValidatorErrors struct {
rules map[string]RuleFunc
}
func New() *ValidatorErrors {
return &ValidatorErrors{
rules: map[string]RuleFunc{},
}
}
func (v *ValidatorErrors) AddRule(tag string, fn RuleFunc) {
v.rules[tag] = fn
}
func (v *ValidatorErrors) RemoveRule(tag string) {
delete(v.rules, tag)
}
func (v *ValidatorErrors) AddDefaultRule(tag string) {
switch tag {
case "required":
v.rules[tag] = func(e validator.FieldError) string {
return fmt.Sprintf("%s is required", e.Field())
}
case "min":
v.rules[tag] = func(e validator.FieldError) string {
return fmt.Sprintf("%s must be at least %s characters", e.Field(), e.Param())
}
case "max":
v.rules[tag] = func(e validator.FieldError) string {
return fmt.Sprintf("%s can't be more than %s characters", e.Field(), e.Param())
}
case "email":
v.rules[tag] = func(e validator.FieldError) string {
return fmt.Sprintf("%s must be a valid email", e.Field())
}
default:
v.rules[tag] = func(e validator.FieldError) string {
return fmt.Sprintf("%s is invalid", e.Field())
}
}
}
func (v *ValidatorErrors) FormatValidationErrors(err error) map[string]string {
errors := map[string]string{}
for _, e := range err.(validator.ValidationErrors) {
if msgFunc, ok := v.rules[e.Tag()]; ok {
errors[e.Field()] = msgFunc(e)
} else {
errors[e.Field()] = "invalid value"
}
}
return errors
}