-
Notifications
You must be signed in to change notification settings - Fork 7
/
options.go
67 lines (55 loc) · 1.57 KB
/
options.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
60
61
62
63
64
65
66
67
package validator
import (
"fmt"
"html/template"
"reflect"
"strings"
vt "github.com/go-playground/validator/v10"
)
// Option is the interface that allows to set configuration options.
type Option func(v *Validator) error
// WithFieldNameTag allows to use the field names specified by the tag instead of the original struct names.
func WithFieldNameTag(tag string) Option {
return func(v *Validator) error {
if tag == "" {
return nil
}
v.v.RegisterTagNameFunc(func(fld reflect.StructField) string {
name := strings.SplitN(fld.Tag.Get(tag), ",", 2)[0]
if name == "-" {
return ""
}
return name
})
return nil
}
}
// WithCustomValidationTags register custom tags and validation functions.
func WithCustomValidationTags(t map[string]vt.FuncCtx) Option {
return func(v *Validator) error {
for tag, fn := range t {
if err := v.v.RegisterValidationCtx(tag, fn); err != nil {
return fmt.Errorf("failed registering custom tag: %w", err)
}
}
return nil
}
}
// WithErrorTemplates sets basic template-based error message translations.
// The argument t maps tags to html templates that uses the Error data.
// These translations takes precedence over the parent library translation object.
func WithErrorTemplates(t map[string]string) Option {
return func(v *Validator) error {
if len(v.tpl) == 0 {
v.tpl = make(map[string]*template.Template, len(t))
}
for tag, tpl := range t {
t, err := template.New(tag).Parse(tpl)
if err != nil {
return fmt.Errorf("failed adding error template: %w", err)
}
v.tpl[tag] = t
}
return nil
}
}