-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdata-validator.js
More file actions
683 lines (637 loc) · 25.9 KB
/
data-validator.js
File metadata and controls
683 lines (637 loc) · 25.9 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
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
// MOST Web Framework 2.0 Codename Blueshift BSD-3-Clause license Copyright (c) 2017-2022, THEMOST LP All rights reserved
/*eslint no-var: "off"*/
// noinspection ES6ConvertVarToLetConst
var _ = require('lodash');
var {sprintf} = require('sprintf-js');
var {LangUtils} = require('@themost/common');
var {DataConfigurationStrategy} = require('./data-configuration');
var {hasOwnProperty} = require('./has-own-property');
/**
* @class
* @property {*} target - Gets or sets the target data object
* @constructor
*/
function DataValidator() {
var context_;
/**
* Sets the current data context.
* @param {DataContext|*} context
*/
this.setContext = function(context) {
context_ = context;
};
/**
* Gets the current data context, if any.
* @returns {DataContext|*}
*/
this.getContext = function() {
return context_;
};
}
function zeroPad_(number, length) {
number = number || 0;
var res = number.toString();
while (res.length < length) {
res = '0' + res;
}
return res;
}
/**
* @class
* @param {string} pattern - A string which represents a regular expression
* @property {string} message - Gets or sets a string which represents a custom validator message.
* @constructor
* @augments DataValidator
* @classdesc Validates a variable against the regular expression provided
*/
function PatternValidator(pattern) {
this.pattern = pattern;
PatternValidator.super_.call(this);
}
LangUtils.inherits(PatternValidator, DataValidator);
PatternValidator.DefaultMessage = 'The value seems to be invalid.';
/**
* Validates the given value and returns a validation result or undefined if the specified value is invalid
* @param val
* @returns {{code: string, message: string, innerMessage: *}|undefined|null}
*/
PatternValidator.prototype.validateSync = function(val) {
if (val == null) {
return null;
}
var valueTo = val;
if (val instanceof Date) {
var year = val.getFullYear();
var month = zeroPad_(val.getMonth() + 1, 2);
var day = zeroPad_(val.getDate(), 2);
var hour = zeroPad_(val.getHours(), 2);
var minute = zeroPad_(val.getMinutes(), 2);
var second = zeroPad_(val.getSeconds(), 2);
var millisecond = zeroPad_(val.getMilliseconds(), 3);
//format timezone
var offset = (new Date()).getTimezoneOffset(),
timezone = (offset>=0 ? '+' : '') + zeroPad_(Math.floor(offset/60),2) + ':' + zeroPad_(offset%60,2);
valueTo = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second + '.' + millisecond + timezone;
}
var re = new RegExp(this.pattern, 'ig');
if (!re.test(valueTo)) {
var innerMessage = null, message = this.message || PatternValidator.DefaultMessage;
if (this.getContext() && (typeof this.getContext().translate === 'function')) {
innerMessage = message;
message = this.getContext().translate(this.message || PatternValidator.DefaultMessage);
}
return {
code:'EPATTERN',
'message':message,
'innerMessage':innerMessage
}
}
};
/**
* @class
* @param {number} length - A number which represents the minimum length
* @property {number} minLength - Gets or sets an integer which represents the minimum length.
* @property {string} message - Gets or sets a string which represents a custom validator message.
* @augments {DataValidator}
* @constructor
* @classdesc Validates a variable which has a length property (e.g. a string) against the minimum length provided
*/
function MinLengthValidator(length) {
this.minLength = length;
MinLengthValidator.super_.call(this);
}
LangUtils.inherits(MinLengthValidator,DataValidator);
MinLengthValidator.DefaultMessage = 'The value is too short. It should have %s characters or more.';
/**
* Validates the given value. If validation fails, the operation will return a validation result.
* @param {*} val
* @returns {{code: string, minLength: number, message:string, innerMessage: string}|undefined|null}
*/
MinLengthValidator.prototype.validateSync = function(val) {
if (val == null) {
return null;
}
if (hasOwnProperty(val, 'length')) {
if (val.length<this.minLength) {
var innerMessage = null, message = sprintf(this.message || MinLengthValidator.DefaultMessage, this.minLength);
if (this.getContext() && (typeof this.getContext().translate === 'function')) {
innerMessage = message;
message = sprintf(this.getContext().translate(this.message || MinLengthValidator.DefaultMessage), this.minLength);
}
return {
code:'EMINLEN',
minLength:this.minLength,
message:message,
innerMessage:innerMessage
}
}
}
};
/**
* @class
* @param {number} length - A number which represents the maximum length
* @augments {DataValidator}
* @property {number} maxLength - Gets or sets an integer which represents the maximum length.
* @property {string} message - Gets or sets a string which represents a custom validator message.
* @constructor
* @classdesc Validates a variable which has a length property (e.g. a string) against the maximum length provided
*/
function MaxLengthValidator(length) {
this.maxLength = length;
MaxLengthValidator.super_.call(this);
}
LangUtils.inherits(MaxLengthValidator, DataValidator);
MaxLengthValidator.DefaultMessage = 'The value is too long. It should have %s characters or fewer.';
/**
* Validates the given value. If validation fails, the operation will return a validation result.
* @param {*} val
* @returns {{code: string, maxLength: number, message:string, innerMessage: string}|undefined|*}
*/
MaxLengthValidator.prototype.validateSync = function(val) {
if (_.isNil(val)) {
return;
}
var innerMessage = null, message = sprintf(this.message || MaxLengthValidator.DefaultMessage, this.maxLength);
if (this.getContext() && (typeof this.getContext().translate === 'function')) {
innerMessage = message;
message = sprintf(this.getContext().translate(this.message || MaxLengthValidator.DefaultMessage), this.maxLength);
}
if (hasOwnProperty(val, 'length')) {
if (val.length>this.maxLength) {
return {
code:'EMAXLEN',
maxLength:this.maxLength,
message: message,
innerMessage:innerMessage
}
}
}
};
/**
* @class
* @param {number|Date|*} min - A value which represents the minimum value
* @augments {DataValidator}
* @property {*} minValue - Gets or sets a value which represents the minimum value.
* @property {string} message - Gets or sets a string which represents a custom validator message.
* @constructor
* @classdesc Validates a value against the minimum value provided
*/
function MinValueValidator(min) {
this.minValue = min;
MinValueValidator.super_.call(this);
}
LangUtils.inherits(MinValueValidator, DataValidator);
MinValueValidator.DefaultMessage = 'The value should be greater than or equal to %s.';
/**
* Validates the given value. If validation fails, the operation will return a validation result.
* @param {*} val
* @returns {{code: string, maxLength: number, message:string, innerMessage: string}|undefined|*}
*/
MinValueValidator.prototype.validateSync = function(val) {
if (val == null) {
return null;
}
var minValue = this.minValue;
if (val instanceof Date) {
minValue = new Date(this.minValue);
}
if (val < minValue) {
var innerMessage = null, message = sprintf(this.message || MinValueValidator.DefaultMessage, this.minValue);
if (this.getContext() && (typeof this.getContext().translate === 'function')) {
innerMessage = message;
message = sprintf(this.getContext().translate(this.message || MinValueValidator.DefaultMessage), this.minValue);
}
return {
code:'EMINVAL',
minValue:this.minValue,
message:message,
innerMessage:innerMessage
}
}
};
/**
* @class
* @param {number|Date|*} max - A value which represents the maximum value
* @augments {DataValidator}
* @property {*} maxValue - Gets or sets a value which represents the maximum value.
* @property {string} message - Gets or sets a string which represents a custom validator message.
* @constructor
* @classdesc Validates a value against the maximum value provided
*/
function MaxValueValidator(max) {
this.maxValue = max;
MaxValueValidator.super_.call(this);
}
LangUtils.inherits(MaxValueValidator, DataValidator);
MaxValueValidator.DefaultMessage = 'The value should be lower or equal to %s.';
/**
* Validates the given value. If validation fails, the operation will return a validation result.
* @param {*} val
* @returns {{code: string, maxLength: number, message:string, innerMessage: string}|undefined|null}
*/
MaxValueValidator.prototype.validateSync = function(val) {
if (val == null) {
return null;
}
var maxValue = this.maxValue;
if (val instanceof Date) {
maxValue = new Date(this.maxValue);
}
if (val > maxValue) {
var innerMessage = null, message = sprintf(this.message || MaxValueValidator.DefaultMessage , this.maxValue);
if (this.getContext() && (typeof this.getContext().translate === 'function')) {
innerMessage = message;
message = sprintf(this.getContext().translate(this.message || MaxValueValidator.DefaultMessage), this.maxValue);
}
return {
code:'EMAXVAL',
maxValue:this.maxValue,
message:message,
innerMessage:innerMessage
}
}
};
/**
* @class
* @param {number|Date|*} min - A value which represents the minimum value
* @param {number|Date|*} max - A value which represents the maximum value
* @augments {DataValidator}
* @property {*} minValue - Gets or sets a value which represents the minimum value
* @property {*} maxValue - Gets or sets a value which represents the maximum value
* @property {string} message - Gets or sets a string which represents a custom validator message.
* @constructor
* @classdesc Validates a value against a minimum and maximum value
*/
function RangeValidator(min,max) {
this.minValue = min;
this.maxValue = max;
RangeValidator.super_.call(this);
}
LangUtils.inherits(RangeValidator, DataValidator);
RangeValidator.DefaultMessage = 'The value should be between %s to %s.';
/**
* Validates the given value. If validation fails, the operation will return a validation result.
* @param {*} val
* @returns {{code: string, maxLength: number, message:string, innerMessage: string}|undefined|*}
*/
RangeValidator.prototype.validateSync = function(val) {
if (val == null) {
return null;
}
var minValidator, maxValidator, minValidation, maxValidation;
if (!_.isNil(this.minValue)) {
minValidator = new MinValueValidator(this.minValue);
minValidation = minValidator.validateSync(val);
}
if (!_.isNil(this.maxValue)) {
maxValidator = new MaxValueValidator(this.maxValue);
maxValidation = maxValidator.validateSync(val);
}
if (minValidator && maxValidator && (minValidation || maxValidation)) {
var innerMessage = null, message = sprintf(this.message || RangeValidator.DefaultMessage, this.minValue, this.maxValue);
if (this.getContext() && (typeof this.getContext().translate === 'function')) {
innerMessage = message;
message = sprintf(this.getContext().translate(this.message || RangeValidator.DefaultMessage), this.minValue, this.maxValue);
}
return {
code:'ERANGE',
maxValue:this.maxValue,
message:message,
innerMessage:innerMessage
}
}
else if (minValidation) {
return minValidation;
}
else if (maxValidation) {
return maxValidation;
}
};
/**
* @class
* @param {string|*} type - The data type which is going to be used for data validation
* @property {*} dataType - Gets or sets the data type which is going to be used for data validation
* @constructor
* @augments {DataValidator}
* @classdesc Validates a value against a pre-defined data type
*/
function DataTypeValidator(type) {
DataTypeValidator.super_.call(this);
/**
* @name DataTypeValidator#type
* @type {*}
*/
Object.defineProperty(this, 'dataType', {
get: function() {
if (typeof type === 'string') {
return this.getContext().getConfiguration().getStrategy(DataConfigurationStrategy).dataTypes[type];
}
else {
return type;
}
}
});
}
LangUtils.inherits(DataTypeValidator, DataValidator);
/**
* @param val
* @returns {*}
*/
DataTypeValidator.prototype.validateSync = function(val) {
var context = this.getContext();
if (typeof this.dataType === 'undefined') {
return null;
}
/**
* @type {{pattern:string,patternMessage:string,minValue:*,maxValue:*,minLength:number,maxLength:number}}
*/
var properties = this.dataType.properties;
if (typeof properties !== 'undefined') {
var validator, validationResult;
//validate pattern if any
if (properties.pattern) {
validator = new PatternValidator(properties.pattern);
validator.setContext(context);
validationResult = validator.validateSync(val);
if (validationResult) {
if (properties.patternMessage) {
validationResult.message = properties.patternMessage;
if (context && (typeof context.translate === 'function')) {
validationResult.innerMessage = validationResult.message;
validationResult.message = context.translate(properties.patternMessage);
}
}
return validationResult;
}
}
if (hasOwnProperty(properties, 'minValue') && hasOwnProperty(properties, 'maxValue')) {
validator = new RangeValidator(properties.minValue, properties.maxValue);
validator.setContext(context);
validationResult = validator.validateSync(val);
if (validationResult) {
return validationResult;
}
}
else if (hasOwnProperty(properties, 'minValue')) {
validator = new MinValueValidator(properties.minValue);
validator.setContext(context);
if (properties.message) {
validator.message = properties.message;
}
validationResult = validator.validateSync(val);
if (validationResult) {
// try to return a localized message
if (context && (typeof context.translate === 'function')) {
validationResult.message = context.translate(properties.patternMessage);
}
return validationResult;
}
}
else if (hasOwnProperty(properties, 'maxValue')) {
validator = new MaxValueValidator(properties.maxValue);
if (properties.message) {
validator.message = properties.message;
}
validator.setContext(context);
validationResult = validator.validateSync(val);
if (validationResult) {
if (context && (typeof context.translate === 'function')) {
validationResult.message = context.translate(properties.patternMessage);
}
return validationResult;
}
}
if (hasOwnProperty(properties, 'minLength')) {
validator = new MinLengthValidator(properties.minLength);
if (properties.message) {
validator.message = properties.message;
}
validator.setContext(context);
validationResult = validator.validateSync(val);
if (validationResult) {
if (context && (typeof context.translate === 'function')) {
validationResult.message = context.translate(properties.patternMessage);
}
return validationResult;
}
}
if (hasOwnProperty(properties, 'maxLength')) {
validator = new MaxLengthValidator(properties.maxLength);
if (properties.message) {
validator.message = properties.message;
}
validator.setContext(context);
validationResult = validator.validateSync(val);
if (validationResult) {
if (context && (typeof context.translate === 'function')) {
validationResult.message = context.translate(properties.patternMessage);
}
return validationResult;
}
}
}
};
/**
* @class
* @classdesc DataValidatorListener is one of the default listeners of MOST data models. Validates data objects against validation rules defined in model attributes.
* @constructor
*/
function DataValidatorListener() {
//
}
/**
* Occurs before creating or updating a data object.
* @param {DataEventArgs|*} event - An object that represents the event arguments passed to this operation.
* @param {Function} callback - A callback function that should be called at the end of this operation. The first argument may be an error if any occurred.
*/
DataValidatorListener.prototype.beforeSave = function(event, callback) {
if (event.state === 4) { return callback(); }
if (event.state === 1) {
return event.model.validateForInsert(event.target).then(function() {
return callback();
}).catch(function(err) {
return callback(err);
});
}
else if (event.state === 2) {
return event.model.validateForUpdate(event.target).then(function() {
return callback();
}).catch(function(err) {
return callback(err);
});
}
else {
return callback();
}
};
/**
* @class
* @augments DataValidator
* @constructor
* @classdesc Validates a required attribute
*/
function RequiredValidator() {
RequiredValidator.super_.call(this);
}
LangUtils.inherits(RequiredValidator, DataValidator);
/**
* Validates the given value. If validation fails, the operation will return a validation result.
* @param {*} val
* @returns {{code: string, maxLength: number, message:string, innerMessage: string}|undefined|*}
*/
RequiredValidator.prototype.validateSync = function(val) {
var invalid = false;
if (_.isNil(val)) {
invalid=true;
}
else if ((typeof val === 'number') && isNaN(val)) {
invalid=true;
}
// validate array
if (Array.isArray(val)) {
if (val.length===0) {
invalid=true;
}
}
if (invalid) {
var innerMessage = null, message = 'A value is required.';
if (this.getContext() && (typeof this.getContext().translate === 'function')) {
innerMessage = message;
message = this.getContext().translate('A value is required.');
}
return {
code:'EREQUIRED',
message:message,
innerMessage:innerMessage
}
}
};
function AsyncExecuteValidator(model, validator) {
AsyncExecuteValidator.super_.call(this);
Object.defineProperty(this, 'model', {
enumerable: false,
configurable: true,
writable: true,
value: model
});
Object.defineProperty(this, 'validator', {
enumerable: false,
configurable: true,
writable: false,
value: validator
});
}
LangUtils.inherits(AsyncExecuteValidator, DataValidator);
AsyncExecuteValidator.prototype.validate = function(value, callback) {
var self = this;
try {
this.validator({
model: this.model,
target: this.target,
value: value
}).then(function (result) {
if (result) {
return callback();
}
var innerMessage = null;
var message = self.message || 'Data validation failed.';
var context = self.getContext();
if (context && (typeof context.translate === 'function')) {
innerMessage = message;
message = context.translate('Data validation failed.');
}
return callback(null, {
code: 'EVALIDATE',
message: message,
innerMessage: innerMessage
});
}).catch(function (error) {
return callback(error);
});
} catch (err) {
return callback(err);
}
}
/**
*
* @param {string} additionalType
* @param {number} state
* @constructor
*/
function JsonTypeValidator(additionalType, state) {
// noinspection JSUnresolvedReference
JsonTypeValidator.super_.call(this);
this.state = state;
this.additionalType = additionalType;
}
LangUtils.inherits(JsonTypeValidator, DataValidator);
/**
*
* @param {*} val
* @param {function(err?: *, validationResult?: *): void} callback
* @returns {void}
*/
JsonTypeValidator.prototype.validate = function(val, callback) {
if (this.additionalType != null) {
// noinspection ES6ConvertVarToLetConst
/**
* @type {DataContext}
*/
var context = this.getContext();
// noinspection ES6ConvertVarToLetConst
var additionalModel = context.model(this.additionalType);
if (additionalModel == null) {
return callback(null, {
code:'E_MODEL',
message: sprintf('The additional model "%s" for Json type cannot be found.', this.additionalType)
});
}
const values = Array.isArray(val) ? val : [val];
const state = this.state;
(async function() {
// noinspection ES6ConvertVarToLetConst
var res;
// noinspection ES6ConvertVarToLetConst
var attributes = additionalModel.attributeNames;
for (const value of values) {
if (value != null) {
const keys = Object.keys(value);
const unknownKeys = keys.filter(function(k) {
return attributes.indexOf(k) < 0;
});
if (unknownKeys.length > 0) {
return {
code:'E_UNKNOWN',
message: sprintf('The target model "%s" does not contain attribute(s) %s.', additionalModel.name, unknownKeys.map(function(k) { return "\"" + k + "\"" }).slice(0, 5).join(', '))
};
}
}
if (state === 1) {
res = await additionalModel.validateForInsert(value);
if (res) return res;
} else if (state === 2) {
res = await additionalModel.validateForUpdate(value);
if (res) return res;
}
}
})().then(function(result) {
return callback(null, result);
}).catch(function(err) {
return callback(err);
});
}
};
module.exports = {
PatternValidator,
DataValidator,
MaxValueValidator,
MinValueValidator,
MaxLengthValidator,
MinLengthValidator,
RangeValidator,
RequiredValidator,
DataTypeValidator,
AsyncExecuteValidator,
DataValidatorListener,
JsonTypeValidator
};