1
|
|
|
package validation |
2
|
|
|
|
3
|
|
|
import ( |
4
|
|
|
"context" |
5
|
|
|
"time" |
6
|
|
|
|
7
|
|
|
"golang.org/x/text/language" |
8
|
|
|
"golang.org/x/text/message/catalog" |
9
|
|
|
) |
10
|
|
|
|
11
|
|
|
// Validator is the main validation service. It can be created by NewValidator constructor. |
12
|
|
|
// Also, you can use singleton version from the package "github.com/muonsoft/validation/validator". |
13
|
|
|
type Validator struct { |
14
|
|
|
scope Scope |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
// ValidatorOption is a base type for configuration options used to create a new instance of Validator. |
18
|
|
|
type ValidatorOption func(validator *Validator) error |
19
|
|
|
|
20
|
|
|
// NewValidator is a constructor for creating an instance of Validator. |
21
|
|
|
// You can configure it by using validator options. |
22
|
|
|
// |
23
|
|
|
// Example |
24
|
|
|
// validator, err := validation.NewValidator( |
25
|
|
|
// validation.DefaultLanguage(language.Russian), // passing default language of translations |
26
|
|
|
// validation.Translations(russian.Messages), // setting up custom or built-in translations |
27
|
|
|
// validation.SetViolationFactory(userViolationFactory), // if you want to override creation of violations |
28
|
|
|
// ) |
29
|
|
|
// |
30
|
|
|
// // don't forget to check for errors |
31
|
|
|
// if err != nil { |
32
|
|
|
// fmt.Println(err) |
33
|
|
|
// } |
34
|
|
|
func NewValidator(options ...ValidatorOption) (*Validator, error) { |
35
|
1 |
|
validator := &Validator{scope: newScope()} |
36
|
|
|
|
37
|
1 |
|
for _, setOption := range options { |
38
|
1 |
|
err := setOption(validator) |
39
|
1 |
|
if err != nil { |
40
|
1 |
|
return nil, err |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
|
44
|
1 |
|
err := validator.scope.translator.init() |
45
|
1 |
|
if err != nil { |
46
|
1 |
|
return nil, err |
47
|
|
|
} |
48
|
|
|
|
49
|
1 |
|
return validator, nil |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
func newScopedValidator(scope Scope) *Validator { |
53
|
1 |
|
return &Validator{scope: scope} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
// DefaultLanguage is used to set up the default language for translation of violation messages. |
57
|
|
|
func DefaultLanguage(tag language.Tag) ValidatorOption { |
58
|
1 |
|
return func(validator *Validator) error { |
59
|
1 |
|
validator.scope.translator.defaultLanguage = tag |
60
|
1 |
|
return nil |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
// Translations is used to load translation messages into the validator. |
65
|
|
|
// |
66
|
|
|
// By default, all violation messages are generated in the English language with pluralization capabilities. |
67
|
|
|
// To use a custom language you have to load translations on validator initialization. |
68
|
|
|
// Built-in translations are available in the sub-packages of the package "github.com/muonsoft/message/translations". |
69
|
|
|
// The translation mechanism is provided by the "golang.org/x/text" package (be aware, it has no stable version yet). |
70
|
|
|
// |
71
|
|
|
// Example |
72
|
|
|
// // import "github.com/muonsoft/validation/message/translations/russian" |
73
|
|
|
// |
74
|
|
|
// validator, err := validation.NewValidator( |
75
|
|
|
// validation.Translations(russian.Messages), |
76
|
|
|
// ) |
77
|
|
|
func Translations(messages map[language.Tag]map[string]catalog.Message) ValidatorOption { |
78
|
1 |
|
return func(validator *Validator) error { |
79
|
1 |
|
return validator.scope.translator.loadMessages(messages) |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
// SetViolationFactory can be used to override the mechanism of violation creation. |
84
|
|
|
func SetViolationFactory(factory ViolationFactory) ValidatorOption { |
85
|
1 |
|
return func(validator *Validator) error { |
86
|
1 |
|
validator.scope.violationFactory = factory |
87
|
|
|
|
88
|
1 |
|
return nil |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
// StoredConstraint option can be used to store a constraint in an internal validator store. |
93
|
|
|
// It can later be used by the validator.ValidateBy method. This can be useful for passing |
94
|
|
|
// custom or prepared constraints to Validatable. |
95
|
|
|
// |
96
|
|
|
// If the constraint already exists, a ConstraintAlreadyStoredError will be returned. |
97
|
|
|
// |
98
|
|
|
// Example |
99
|
|
|
// validator, err := validation.NewValidator( |
100
|
|
|
// validation.StoredConstraint("isTagExists", isTagExistsConstraint) |
101
|
|
|
// ) |
102
|
|
|
// if err != nil { |
103
|
|
|
// log.Fatal(err) |
104
|
|
|
// } |
105
|
|
|
// |
106
|
|
|
// s := " |
107
|
|
|
// err = validator.ValidateString(&s, validator.ValidateBy("isTagExists")) |
108
|
|
|
func StoredConstraint(key string, constraint Constraint) ValidatorOption { |
109
|
1 |
|
return func(validator *Validator) error { |
110
|
1 |
|
if _, exists := validator.scope.constraints[key]; exists { |
111
|
1 |
|
return ConstraintAlreadyStoredError{Key: key} |
112
|
|
|
} |
113
|
|
|
|
114
|
1 |
|
validator.scope.constraints[key] = constraint |
115
|
|
|
|
116
|
1 |
|
return nil |
117
|
|
|
} |
118
|
|
|
} |
119
|
|
|
|
120
|
|
|
// Validate is the main validation method. It accepts validation arguments. Arguments can be |
121
|
|
|
// used to tune up the validation process or to pass values of a specific type. |
122
|
|
|
func (validator *Validator) Validate(arguments ...Argument) error { |
123
|
1 |
|
args := &Arguments{scope: validator.scope} |
124
|
1 |
|
for _, argument := range arguments { |
125
|
1 |
|
err := argument.set(args) |
126
|
1 |
|
if err != nil { |
127
|
1 |
|
return err |
128
|
|
|
} |
129
|
|
|
} |
130
|
|
|
|
131
|
1 |
|
violations := make(ViolationList, 0) |
132
|
1 |
|
for _, validate := range args.validators { |
133
|
1 |
|
vs, err := validate(args.scope) |
134
|
1 |
|
if err != nil { |
135
|
1 |
|
return err |
136
|
|
|
} |
137
|
1 |
|
violations = append(violations, vs...) |
138
|
|
|
} |
139
|
|
|
|
140
|
1 |
|
return violations.AsError() |
141
|
|
|
} |
142
|
|
|
|
143
|
|
|
// ValidateValue is an alias for validating a single value of any supported type. |
144
|
|
|
func (validator *Validator) ValidateValue(value interface{}, options ...Option) error { |
145
|
1 |
|
return validator.Validate(Value(value, options...)) |
146
|
|
|
} |
147
|
|
|
|
148
|
|
|
// ValidateBool is an alias for validating a single boolean value. |
149
|
|
|
func (validator *Validator) ValidateBool(value *bool, options ...Option) error { |
150
|
1 |
|
return validator.Validate(Bool(value, options...)) |
151
|
|
|
} |
152
|
|
|
|
153
|
|
|
// ValidateNumber is an alias for validating a single numeric value (integer or float). |
154
|
|
|
func (validator *Validator) ValidateNumber(value interface{}, options ...Option) error { |
155
|
1 |
|
return validator.Validate(Number(value, options...)) |
156
|
|
|
} |
157
|
|
|
|
158
|
|
|
// ValidateString is an alias for validating a single string value. |
159
|
|
|
func (validator *Validator) ValidateString(value *string, options ...Option) error { |
160
|
1 |
|
return validator.Validate(String(value, options...)) |
161
|
|
|
} |
162
|
|
|
|
163
|
|
|
// ValidateIterable is an alias for validating a single iterable value (an array, slice, or map). |
164
|
|
|
func (validator *Validator) ValidateIterable(value interface{}, options ...Option) error { |
165
|
1 |
|
return validator.Validate(Iterable(value, options...)) |
166
|
|
|
} |
167
|
|
|
|
168
|
|
|
// ValidateCountable is an alias for validating a single countable value (an array, slice, or map). |
169
|
|
|
func (validator *Validator) ValidateCountable(count int, options ...Option) error { |
170
|
1 |
|
return validator.Validate(Countable(count, options...)) |
171
|
|
|
} |
172
|
|
|
|
173
|
|
|
// ValidateTime is an alias for validating a single time value. |
174
|
|
|
func (validator *Validator) ValidateTime(value *time.Time, options ...Option) error { |
175
|
1 |
|
return validator.Validate(Time(value, options...)) |
176
|
|
|
} |
177
|
|
|
|
178
|
|
|
// ValidateEach is an alias for validating each value of an iterable (an array, slice, or map). |
179
|
|
|
func (validator *Validator) ValidateEach(value interface{}, options ...Option) error { |
180
|
1 |
|
return validator.Validate(Each(value, options...)) |
181
|
|
|
} |
182
|
|
|
|
183
|
|
|
// ValidateEachString is an alias for validating each value of a strings slice. |
184
|
|
|
func (validator *Validator) ValidateEachString(values []string, options ...Option) error { |
185
|
1 |
|
return validator.Validate(EachString(values, options...)) |
186
|
|
|
} |
187
|
|
|
|
188
|
|
|
// ValidateValidatable is an alias for validating value that implements the Validatable interface. |
189
|
|
|
func (validator *Validator) ValidateValidatable(validatable Validatable, options ...Option) error { |
190
|
1 |
|
return validator.Validate(Valid(validatable, options...)) |
191
|
|
|
} |
192
|
|
|
|
193
|
|
|
// Context returns context from current validation scope. By default it returns context.Background. |
194
|
|
|
// You can create scoped validator with context by calling WithContext method. |
195
|
|
|
func (validator *Validator) Context() context.Context { |
196
|
1 |
|
return validator.scope.context |
197
|
|
|
} |
198
|
|
|
|
199
|
|
|
// WithContext method creates a new scoped validator with a given context. You can use this method to pass |
200
|
|
|
// a context value to all used constraints. |
201
|
|
|
// |
202
|
|
|
// Example |
203
|
|
|
// err := validator.WithContext(request.Context()).Validate( |
204
|
|
|
// String(&s, it.IsNotBlank()), // now all called constraints will use passed context in their methods |
205
|
|
|
// ) |
206
|
|
|
func (validator *Validator) WithContext(ctx context.Context) *Validator { |
207
|
1 |
|
return newScopedValidator(validator.scope.withContext(ctx)) |
208
|
|
|
} |
209
|
|
|
|
210
|
|
|
// WithLanguage method creates a new scoped validator with a given language tag. All created violations |
211
|
|
|
// will be translated into this language. |
212
|
|
|
// |
213
|
|
|
// Example |
214
|
|
|
// err := validator.WithLanguage(language.Russian).Validate( |
215
|
|
|
// validation.ValidateString(&s, it.IsNotBlank()), // violation from this constraint will be translated |
216
|
|
|
// ) |
217
|
|
|
func (validator *Validator) WithLanguage(tag language.Tag) *Validator { |
218
|
1 |
|
return newScopedValidator(validator.scope.withLanguage(tag)) |
219
|
|
|
} |
220
|
|
|
|
221
|
|
|
// AtProperty method creates a new scoped validator with injected property name element to scope property path. |
222
|
|
|
func (validator *Validator) AtProperty(name string) *Validator { |
223
|
1 |
|
return newScopedValidator(validator.scope.atProperty(name)) |
224
|
|
|
} |
225
|
|
|
|
226
|
|
|
// AtIndex method creates a new scoped validator with injected array index element to scope property path. |
227
|
|
|
func (validator *Validator) AtIndex(index int) *Validator { |
228
|
1 |
|
return newScopedValidator(validator.scope.atIndex(index)) |
229
|
|
|
} |
230
|
|
|
|
231
|
|
|
// BuildViolation can be used to build a custom violation on the client-side. |
232
|
|
|
// |
233
|
|
|
// Example |
234
|
|
|
// err := validator.BuildViolation("", ""). |
235
|
|
|
// AddParameter("key", "value"). |
236
|
|
|
// CreateViolation() |
237
|
|
|
func (validator *Validator) BuildViolation(code, message string) *ViolationBuilder { |
238
|
1 |
|
return validator.scope.BuildViolation(code, message) |
239
|
|
|
} |
240
|
|
|
|
241
|
|
|
// ValidateBy is used to get the constraint from the internal validator store. |
242
|
|
|
// If the constraint does not exist, then the validator will |
243
|
|
|
// return a ConstraintNotFoundError during the validation process. |
244
|
|
|
// For storing a constraint you should use the StoreConstraint method. |
245
|
|
|
func (validator *Validator) ValidateBy(constraintKey string) Constraint { |
246
|
1 |
|
if constraint, exists := validator.scope.constraints[constraintKey]; exists { |
247
|
1 |
|
return constraint |
248
|
|
|
} |
249
|
|
|
|
250
|
1 |
|
return notFoundConstraint{key: constraintKey} |
251
|
|
|
} |
252
|
|
|
|