-
-
Notifications
You must be signed in to change notification settings - Fork 128
/
validation-group.js
497 lines (452 loc) · 17.9 KB
/
validation-group.js
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
import {metadata} from 'aurelia-metadata';
import {ValidationGroupBuilder} from './validation-group-builder';
import {ValidationResult} from './validation-result';
import {ValidationMetadata} from './decorators';
/**
* Encapsulates validation rules and their current validation state for a given subject
* @class ValidationGroup
* @constructor
*/
export class ValidationGroup {
/**
* Instantiates a new {ValidationGroup}
* @param subject The subject to evaluate
* @param observerLocator The observerLocator used to monitor changes on the subject
* @param config The configuration
*/
constructor(subject, observerLocator, config) {
let validationMetadata;
this.result = new ValidationResult();
this.subject = subject;
this.validationProperties = [];
this.config = config;
this.builder = new ValidationGroupBuilder(observerLocator, this);
this.onValidateCallbacks = [];
this.onPropertyValidationCallbacks = [];
this.isValidating = false;
this.onDestroy = config.onLocaleChanged(() => {
this.validate(false, true);
});
validationMetadata = metadata.getOwn(ValidationMetadata.metadataKey, this.subject);
if (validationMetadata) {
validationMetadata.setup(this);
}
}
destroy() {
this.validationProperties.forEach(prop => {
prop.destroy();
});
this.onDestroy();
// TODO: what else needs to be done for proper cleanup?
}
clear() {
this.validationProperties.forEach((prop) => {
prop.clear();
});
this.result.clear();
}
onBreezeEntity() {
let breezeEntity = this.subject;
let me = this;
let errors;
this.onPropertyValidate((propertyBindingPath) => {
this.passes(() => {
breezeEntity.entityAspect.validateProperty(propertyBindingPath);
errors = breezeEntity.entityAspect.getValidationErrors(propertyBindingPath);
if (errors.length === 0) {
return true;
}
return errors[0].errorMessage;
});
});
this.onValidate(() => {
breezeEntity.entityAspect.validateEntity();
return {};
});
breezeEntity.entityAspect.validationErrorsChanged.subscribe(() => {
breezeEntity.entityAspect.getValidationErrors().forEach((validationError) => {
let propertyName = validationError.propertyName;
let currentResultProp;
if (!me.result.properties[propertyName]) {
//set up empty validation on the property
me.ensure(propertyName);
}
currentResultProp = me.result.addProperty(propertyName);
if (currentResultProp.isValid) {
currentResultProp.setValidity({
isValid: false,
message: validationError.errorMessage,
failingRule: 'breeze',
latestValue: currentResultProp.latestValue
}, true);
}
});
});
}
/**
* Causes complete re-evaluation: gets the latest value, marks the property as 'dirty' (unless false is passed), runs validation rules asynchronously and updates this.result
* @returns {Promise} A promise that fulfils when valid, rejects when invalid.
*/
validate(forceDirty = true, forceExecution = true) {
this.isValidating = true;
let promise = Promise.resolve(true);
// FIXME: Need to refactor this to not use promises and loop over them
/*eslint-disable */
for (let i = this.validationProperties.length - 1; i >= 0; i--) {
let validatorProperty = this.validationProperties[i];
promise = promise.then(() => {
return validatorProperty.validateCurrentValue(forceDirty, forceExecution);
});
}
/*eslint-enable */
promise = promise.catch(() => {
throw Error('Should never get here: a validation property should always resolve to true/false!');
});
this.onValidateCallbacks.forEach((onValidateCallback) => {
promise = promise.then(() => {
return this.config.locale();
}).then((locale) => {
return Promise.resolve(onValidateCallback.validationFunction()).then((callbackResult) => {
for (let prop in callbackResult) {
let resultProp;
let result;
let newPropResult;
if (!this.result.properties[prop]) {
//set up empty validation on the property
this.ensure(prop);
}
resultProp = this.result.addProperty(prop);
result = callbackResult[prop];
newPropResult = {
latestValue: resultProp.latestValue
};
if (result === true || result === null || result === '') {
if (!resultProp.isValid && resultProp.failingRule === 'onValidateCallback') {
newPropResult.failingRule = null;
newPropResult.message = '';
newPropResult.isValid = true;
resultProp.setValidity(newPropResult, true);
}
} else {
if (resultProp.isValid) {
newPropResult.failingRule = 'onValidateCallback';
newPropResult.isValid = false;
if (typeof(result) === 'string') {
newPropResult.message = result;
} else {
newPropResult.message = locale.translate(newPropResult.failingRule);
}
resultProp.setValidity(newPropResult, true);
}
}
}
this.result.checkValidity();
},
(a, b, c, d, e) => {
this.result.isValid = false;
if (onValidateCallback.validationFunctionFailedCallback) {
onValidateCallback.validationFunctionFailedCallback(a, b, c, d, e);
}
});
});
});
promise = promise.then(() => {
this.isValidating = false;
if (this.result.isValid) {
return Promise.resolve(this.result);
}
return Promise.reject(this.result);
});
return promise;
}
onValidate(validationFunction, validationFunctionFailedCallback) {
this.onValidateCallbacks.push({validationFunction, validationFunctionFailedCallback});
return this;
}
onPropertyValidate(validationFunction) {
this.onPropertyValidationCallbacks.push(validationFunction);
return this;
}
/**
* Adds a validation property for the specified path
* @param {String} bindingPath the path of the property/field, for example 'firstName' or 'address.muncipality.zipCode'
* @param configCallback a configuration callback
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
ensure(bindingPath, configCallback) {
this.builder.ensure(bindingPath, configCallback);
this.onPropertyValidationCallbacks.forEach((callback) => {
callback(bindingPath);
});
return this;
}
/**
* Adds a validation rule that checks a value for being 'isNotEmpty', 'required'
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
isNotEmpty() {
return this.builder.isNotEmpty();
}
/**
* Adds a validation rule that allows a value to be empty/null
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
canBeEmpty() {
return this.builder.canBeEmpty();
}
/**
* Adds a validation rule that checks a value for being greater than or equal to a threshold
* @param minimumValue the threshold
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
isGreaterThanOrEqualTo(minimumValue) {
return this.builder.isGreaterThanOrEqualTo(minimumValue);
}
/**
* Adds a validation rule that checks a value for being greater than a threshold
* @param minimumValue the threshold
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
isGreaterThan(minimumValue) {
return this.builder.isGreaterThan(minimumValue);
}
/**
* Adds a validation rule that checks a value for being greater than or equal to a threshold, and less than or equal to another threshold
* @param minimumValue The minimum threshold
* @param maximumValue The isLessThanOrEqualTo threshold
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
isBetween(minimumValue, maximumValue) {
return this.builder.isBetween(minimumValue, maximumValue);
}
/**
* Adds a validation rule that checks a value for being less than a threshold
* @param maximumValue The threshold
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
isLessThanOrEqualTo(maximumValue) {
return this.builder.isLessThanOrEqualTo(maximumValue);
}
/**
* Adds a validation rule that checks a value for being less than or equal to a threshold
* @param maximumValue The threshold
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
isLessThan(maximumValue) {
return this.builder.isLessThan(maximumValue);
}
/**
* Adds a validation rule that checks a value for being equal to a threshold
* @param otherValue The threshold
* @param otherValueLabel Optional: a label to use in the validation message
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
isEqualTo(otherValue, otherValueLabel) {
return this.builder.isEqualTo(otherValue, otherValueLabel);
}
/**
* Adds a validation rule that checks a value for not being equal to a threshold
* @param otherValue The threshold
* @param otherValueLabel Optional: a label to use in the validation message
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
isNotEqualTo(otherValue, otherValueLabel) {
return this.builder.isNotEqualTo(otherValue, otherValueLabel);
}
/**
* Adds a validation rule that checks a value for being a valid isEmail address
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
isEmail() {
return this.builder.isEmail();
}
/**
* Adds a validation rule that checks a value for being a valid URL
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
isURL() {
return this.builder.isURL();
}
/**
* Adds a validation rule that checks a value for being equal to at least one other value in a particular collection
* @param collection The threshold
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
isIn(collection) {
return this.builder.isIn(collection);
}
/**
* Adds a validation rule that checks a value for having a length greater than or equal to a specified threshold
* @param minimumValue The threshold
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
hasMinLength(minimumValue) {
return this.builder.hasMinLength(minimumValue);
}
/**
* Adds a validation rule that checks a value for having a length less than a specified threshold
* @param maximumValue The threshold
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
hasMaxLength(maximumValue) {
return this.builder.hasMaxLength(maximumValue);
}
/**
* Adds a validation rule that checks a value for having a length greater than or equal to a specified threshold and less than another threshold
* @param minimumValue The min threshold
* @param maximumValue The max threshold
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
hasLengthBetween(minimumValue, maximumValue) {
return this.builder.hasLengthBetween(minimumValue, maximumValue);
}
/**
* Adds a validation rule that checks a value for being numeric, this includes formatted numbers like '-3,600.25'
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
isNumber() {
return this.builder.isNumber();
}
/**
* Adds a validation rule that checks a value for containing not a single whitespace
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
containsNoSpaces() {
return this.builder.containsNoSpaces();
}
/**
* Adds a validation rule that checks a value for being strictly numeric, this excludes formatted numbers like '-3,600.25'
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
containsOnlyDigits() {
return this.builder.containsOnlyDigits();
}
containsOnly(regex) {
return this.builder.containsOnly(regex);
}
containsOnlyAlpha() {
return this.builder.containsOnlyAlpha();
}
containsOnlyAlphaOrWhitespace() {
return this.builder.containsOnlyAlphaOrWhitespace();
}
containsOnlyLetters() {
return this.builder.containsOnlyAlpha();
}
containsOnlyLettersOrWhitespace() {
return this.builder.containsOnlyAlphaOrWhitespace();
}
/**
* Adds a validation rule that checks a value for only containing alphanumerical characters
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
containsOnlyAlphanumerics() {
return this.builder.containsOnlyAlphanumerics();
}
/**
* Adds a validation rule that checks a value for only containing alphanumerical characters or whitespace
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
containsOnlyAlphanumericsOrWhitespace() {
return this.builder.containsOnlyAlphanumericsOrWhitespace();
}
/**
* Adds a validation rule that checks a value for being a strong password. A strong password contains at least the specified of the following groups: lowercase characters, uppercase characters, digits and special characters.
* @param minimumComplexityLevel {Number} Optionally, specifiy the number of groups to match. Default is 4.
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
isStrongPassword(minimumComplexityLevel) {
return this.builder.isStrongPassword(minimumComplexityLevel);
}
/**
* Adds a validation rule that checks a value for matching a particular regex
* @param regex the regex to match
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
matches(regex) {
return this.builder.matches(regex);
}
/**
* Adds a validation rule that checks a value for passing a custom function
* @param customFunction {Function} The custom function that needs to pass, that takes two arguments: newValue (the value currently being evaluated) and optionally: threshold, and returns true/false.
* @param threshold {Object} An optional threshold that will be passed to the customFunction
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
passes(customFunction, threshold) {
return this.builder.passes(customFunction, threshold);
}
/**
* Adds the {ValidationRule}
* @param validationRule {ValudationRule} The rule that needs to pass
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
passesRule(validationRule) {
return this.builder.passesRule(validationRule);
}
/**
* Specifies that the next validation rules only need to be evaluated when the specified conditionExpression is true
* @param conditionExpression {Function} a function that returns true of false.
* @param threshold {Object} an optional treshold object that is passed to the conditionExpression
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
if(conditionExpression, threshold) {
return this.builder.if(conditionExpression, threshold);
}
/**
* Specifies that the next validation rules only need to be evaluated when the previously specified conditionExpression is false.
* See: if (conditionExpression, threshold)
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
else() {
return this.builder.else();
}
/**
* Specifies that the execution of next validation rules no longer depend on the the previously specified conditionExpression.
* See: if (conditionExpression, threshold)
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
endIf() {
return this.builder.endIf();
}
/**
* Specifies that the next validation rules only need to be evaluated when they are preceded by a case that matches the conditionExpression
* @param conditionExpression {Function} a function that returns a case label to execute. This is optional, when omitted the case label will be matched using the underlying property's value
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
switch(conditionExpression) {
return this.builder.switch(conditionExpression);
}
/**
* Specifies that the next validation rules only need to be evaluated when the caseLabel matches the value returned by a preceding switch statement
* See: switch(conditionExpression)
* @param caseLabel {Object} the case label
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
case(caseLabel) {
return this.builder.case(caseLabel);
}
/**
* Specifies that the next validation rules only need to be evaluated when not other caseLabel matches the value returned by a preceding switch statement
* See: switch(conditionExpression)
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
default() {
return this.builder.default();
}
/**
* Specifies that the execution of next validation rules no longer depend on the the previously specified conditionExpression.
* See: switch(conditionExpression)
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
endSwitch() {
return this.builder.endSwitch();
}
/**
* Specifies that the execution of the previous validation rule should use the specified error message if it fails
* @param message either a static string or a function that takes two arguments: newValue (the value that has been evaluated) and threshold.
* @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API
*/
withMessage(message) {
return this.builder.withMessage(message);
}
}