-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathcore-validator.js
625 lines (603 loc) · 24.6 KB
/
core-validator.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
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
import { get, set } from '@ember/object';
import { getOwner } from '@ember/application';
import { capitalize } from '@ember/string';
import { isEmpty, isBlank, isPresent, typeOf, isEqual } from '@ember/utils';
import { A, isArray } from '@ember/array';
import PostalCodesRegex from 'ember-model-validator/postal-codes-regex';
import MessagesEn from '../messages/en';
import MessagesAr from '../messages/ar';
import MessagesFr from '../messages/fr';
import MessagesEs from '../messages/es';
import MessagesPtbr from '../messages/pt-br';
import MessagesUk from '../messages/uk';
import MessagesHu from '../messages/hu';
import MessagesSr from '../messages/sr';
import MessagesSrCyrl from '../messages/sr-cyrl';
const Messages = {
en: MessagesEn,
ar: MessagesAr,
fr: MessagesFr,
es: MessagesEs,
'pt-br': MessagesPtbr,
uk: MessagesUk,
hu: MessagesHu,
sr: MessagesSr,
'sr-cyrl': MessagesSrCyrl,
};
function coreValidator(constructor) {
return class CoreValidator extends constructor {
validationErrors = {};
isValidNow = true;
addErrors = true;
_validationMessages = {};
// to be implemented
// clearErrors() {
// }
// to be implemented
// pushErrors(_errors) {
// }
validate(options = {}) {
let validations = this['validations'];
// Clean all the current errors
// Clean all the current errors
this['clearErrors']();
// Validate but not set errors
if (Object.prototype.hasOwnProperty.call(options, 'addErrors')) {
set(this, 'addErrors', options['addErrors']);
} else {
set(this, 'addErrors', true);
}
// Call validators defined on each property
for (let property in validations) {
for (let validation in validations[property]) {
if (this._exceptOrOnly(property, validation, options)) {
let validationName = capitalize(validation);
// allowBlank option
if (get(validations[property], `${validation}.allowBlank`) && isEmpty(get(this, property))) {
continue;
}
// conditional functions
let conditionalFunction = get(validations[property], `${validation}.if`);
if (conditionalFunction && !conditionalFunction(property, get(this, property), this)) {
continue;
}
this[`_validate${validationName}`](property, validations[property]);
}
}
}
// Check if it's valid or not
if (!this.isValidNow) {
let errors = this.validationErrors;
// It may be invalid because of its relations
if (this.addErrors && Object.keys(errors).length !== 0) {
this['pushErrors'](errors);
}
return false;
} else {
return true;
}
}
/**** Validators ****/
_validateCustom(property, validation) {
validation = isArray(validation.custom) ? validation.custom : [validation.custom];
for (let i = 0; i < validation.length; i++) {
let customValidator = this._getCustomValidator(validation[i]);
if (customValidator) {
let passedCustomValidation = customValidator(property, get(this, property), this);
if (!passedCustomValidation) {
set(this, 'isValidNow', false);
this._addToErrors(property, validation[i], this._validationMessages.customValidationMessage);
}
}
}
}
_validatePresence(property, validation) {
let propertyValue = get(this, property);
// If the property is an async relationship.
if (this._modelRelations() && !isBlank(this._modelRelations()[property])) {
propertyValue = get(this, `${property}.content`);
}
if (isBlank(propertyValue)) {
set(this, 'isValidNow', false);
this._addToErrors(property, validation.presence, this._validationMessages.presenceMessage);
}
}
_validateAbsence(property, validation) {
if (isPresent(get(this, property))) {
set(this, 'isValidNow', false);
this._addToErrors(property, validation.absence, this._validationMessages.absenceMessage);
}
}
_validateAcceptance(property, validation) {
let propertyValue = get(this, property),
accept = validation.acceptance.accept || [1, '1', true];
if (!this._includes(A(accept), propertyValue)) {
set(this, 'isValidNow', false);
this._addToErrors(property, validation.acceptance, this._validationMessages.acceptanceMessage);
}
}
_validateFormat(property, validation) {
let withRegexp = validation.format.with;
if (get(this, property) && String(get(this, property)).match(withRegexp) === null) {
set(this, 'isValidNow', false);
this._addToErrors(property, validation.format, this._validationMessages.formatMessage);
}
}
_validateEmail(property, validation) {
if (
!get(this, property) ||
String(get(this, property)).match(
/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
) === null
) {
set(this, 'isValidNow', false);
this._addToErrors(property, validation.email, this._validationMessages.mailMessage);
}
}
_validateZipCode(property, validation) {
const DEFAULT_COUNTRY_CODE = 'US';
let propertyValue = get(this, property);
let countryCode = DEFAULT_COUNTRY_CODE;
if (Object.prototype.hasOwnProperty.call(validation.zipCode, 'countryCode')) {
countryCode = validation.zipCode.countryCode;
}
if (isArray(countryCode)) {
countryCode.forEach(function (code) {
let postalCodeRegexp = PostalCodesRegex[code];
if (typeof postalCodeRegexp === 'undefined') {
postalCodeRegexp = PostalCodesRegex[DEFAULT_COUNTRY_CODE];
}
if (!propertyValue || String(propertyValue).match(postalCodeRegexp) === null) {
set(this, 'isValidNow', false);
this._addToErrors(property, validation.zipCode, this._validationMessages.zipCodeMessage);
}
});
} else {
let postalCodeRegexp = PostalCodesRegex[countryCode];
if (typeof postalCodeRegexp === 'undefined') {
postalCodeRegexp = PostalCodesRegex[DEFAULT_COUNTRY_CODE];
}
if (!propertyValue || String(propertyValue).match(postalCodeRegexp) === null) {
set(this, 'isValidNow', false);
this._addToErrors(property, validation.zipCode, this._validationMessages.zipCodeMessage);
}
}
}
_validateColor(property, validation) {
let propertyValue = get(this, property);
if (!propertyValue || String(propertyValue).match(/([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/i) === null) {
set(this, 'isValidNow', false);
this._addToErrors(property, validation.color, this._validationMessages.colorMessage);
}
}
_validateURL(property, validation) {
let propertyValue = get(this, property);
if (
!propertyValue ||
String(propertyValue).match(
/^((http|https):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?$/
) === null
) {
set(this, 'isValidNow', false);
this._addToErrors(property, validation.URL, this._validationMessages.URLMessage);
}
}
_validateSubdomain(property, validation) {
let propertyValue = get(this, property),
reserved = validation.subdomain.reserved || [];
if (
!propertyValue ||
String(propertyValue).match(/^[a-z\d]+([-_][a-z\d]+)*$/i) === null ||
reserved.indexOf(propertyValue) !== -1
) {
set(this, 'isValidNow', false);
this._addToErrors(property, validation.subdomain, this._validationMessages.subdomainMessage);
}
}
_validateDate(property, validation) {
let propertyValue = new Date(get(this, property));
if (isNaN(propertyValue.getTime())) {
set(this, 'isValidNow', false);
this._addToErrors(property, validation.date, this._validationMessages.dateMessage);
return;
}
if (Object.prototype.hasOwnProperty.call(validation.date, 'before') && validation.date.before) {
if (propertyValue.getTime() >= new Date(validation.date.before).getTime()) {
set(this, 'isValidNow', false);
let context = { date: new Date(validation.date.before) };
validation.date.interpolatedValue = validation.date.before;
this._addToErrors(
property,
validation.date,
this._formatMessage(this._validationMessages.dateBeforeMessage, context)
);
}
}
if (Object.prototype.hasOwnProperty.call(validation.date, 'after') && validation.date.after) {
if (propertyValue.getTime() <= new Date(validation.date.after).getTime()) {
set(this, 'isValidNow', false);
let context = { date: new Date(validation.date.after) };
validation.date.interpolatedValue = validation.date.after;
this._addToErrors(
property,
validation.date,
this._formatMessage(this._validationMessages.dateAfterMessage, context)
);
}
}
}
_validateNumericality(property, validation) {
let propertyValue = get(this, property);
if (!this._isNumber(get(this, property))) {
set(this, 'isValidNow', false);
this._addToErrors(property, validation.numericality, this._validationMessages.numericalityMessage);
}
if (
Object.prototype.hasOwnProperty.call(validation.numericality, 'onlyInteger') &&
validation.numericality.onlyInteger
) {
if (!/^[+-]?\d+$/.test(propertyValue)) {
set(this, 'isValidNow', false);
this._addToErrors(property, validation.numericality, this._validationMessages.numericalityOnlyIntegerMessage);
}
}
if (Object.prototype.hasOwnProperty.call(validation.numericality, 'even') && validation.numericality.even) {
if (propertyValue % 2 !== 0) {
set(this, 'isValidNow', false);
this._addToErrors(property, validation.numericality, this._validationMessages.numericalityEvenMessage);
}
}
if (Object.prototype.hasOwnProperty.call(validation.numericality, 'odd') && validation.numericality.odd) {
if (propertyValue % 2 === 0) {
set(this, 'isValidNow', false);
this._addToErrors(property, validation.numericality, this._validationMessages.numericalityOddMessage);
}
}
if (
Object.prototype.hasOwnProperty.call(validation.numericality, 'greaterThan') &&
this._isNumber(validation.numericality.greaterThan)
) {
if (propertyValue <= validation.numericality.greaterThan) {
set(this, 'isValidNow', false);
let context = { count: validation.numericality.greaterThan };
validation.numericality.interpolatedValue = validation.numericality.greaterThan;
this._addToErrors(
property,
validation.numericality,
this._formatMessage(this._validationMessages.numericalityGreaterThanMessage, context)
);
}
}
if (
Object.prototype.hasOwnProperty.call(validation.numericality, 'greaterThanOrEqualTo') &&
this._isNumber(validation.numericality.greaterThanOrEqualTo)
) {
if (propertyValue < validation.numericality.greaterThanOrEqualTo) {
set(this, 'isValidNow', false);
let context = { count: validation.numericality.greaterThanOrEqualTo };
validation.numericality.interpolatedValue = validation.numericality.greaterThanOrEqualTo;
this._addToErrors(
property,
validation.numericality,
this._formatMessage(this._validationMessages.numericalityGreaterThanOrEqualToMessage, context)
);
}
}
if (
Object.prototype.hasOwnProperty.call(validation.numericality, 'equalTo') &&
this._isNumber(validation.numericality.equalTo)
) {
if (propertyValue !== validation.numericality.equalTo) {
set(this, 'isValidNow', false);
let context = { count: validation.numericality.equalTo };
validation.numericality.interpolatedValue = validation.numericality.equalTo;
this._addToErrors(
property,
validation.numericality,
this._formatMessage(this._validationMessages.numericalityEqualToMessage, context)
);
}
}
if (
Object.prototype.hasOwnProperty.call(validation.numericality, 'lessThan') &&
this._isNumber(validation.numericality.lessThan)
) {
if (propertyValue >= validation.numericality.lessThan) {
set(this, 'isValidNow', false);
let context = { count: validation.numericality.lessThan };
validation.numericality.interpolatedValue = validation.numericality.lessThan;
this._addToErrors(
property,
validation.numericality,
this._formatMessage(this._validationMessages.numericalityLessThanMessage, context)
);
}
}
if (
Object.prototype.hasOwnProperty.call(validation.numericality, 'lessThanOrEqualTo') &&
this._isNumber(validation.numericality.lessThanOrEqualTo)
) {
if (propertyValue > validation.numericality.lessThanOrEqualTo) {
set(this, 'isValidNow', false);
let context = { count: validation.numericality.lessThanOrEqualTo };
validation.numericality.interpolatedValue = validation.numericality.lessThanOrEqualTo;
this._addToErrors(
property,
validation.numericality,
this._formatMessage(this._validationMessages.numericalityLessThanOrEqualToMessage, context)
);
}
}
}
_validateExclusion(property, validation) {
if (Object.prototype.hasOwnProperty.call(validation.exclusion, 'in')) {
if (validation.exclusion.in.indexOf(get(this, property)) !== -1) {
set(this, 'isValidNow', false);
this._addToErrors(property, validation.exclusion, this._validationMessages.exclusionMessage);
}
}
}
_validateInclusion(property, validation) {
if (Object.prototype.hasOwnProperty.call(validation.inclusion, 'in')) {
if (validation.inclusion.in.indexOf(get(this, property)) === -1) {
set(this, 'isValidNow', false);
this._addToErrors(property, validation.inclusion, this._validationMessages.inclusionMessage);
}
}
}
_validateMatch(property, validation) {
let matching = validation.match.attr || validation.match,
propertyValue = get(this, property),
matchingValue = get(this, matching);
if (propertyValue !== matchingValue) {
set(this, 'isValidNow', false);
let matchingUnCamelCase = this._unCamelCase(matching);
let context = { match: matchingUnCamelCase };
if (typeOf(validation.match) === 'object') {
validation.match.interpolatedValue = matchingUnCamelCase;
}
this._addToErrors(
property,
validation.match,
this._formatMessage(this._validationMessages.matchMessage, context)
);
}
}
// Length Validator
_validateLength(property, validation) {
let propertyValue = get(this, property),
stringLength = !propertyValue ? 0 : String(propertyValue).length,
validationType = typeOf(validation.length);
if (validationType === 'number') {
validation.length = { is: validation.length };
this._exactLength(stringLength, property, validation);
} else if (validationType === 'array') {
validation.length = { minimum: validation.length[0], maximum: validation.length[1] };
this._rangeLength(stringLength, property, validation);
} else if (validationType === 'object') {
if (Object.prototype.hasOwnProperty.call(validation.length, 'is')) {
this._exactLength(stringLength, property, validation);
} else {
this._rangeLength(stringLength, property, validation);
}
}
}
_exactLength(stringLength, property, validation) {
if (stringLength !== validation.length.is) {
set(this, 'isValidNow', false);
let context = { count: validation.length.is };
validation.length.interpolatedValue = validation.length.is;
this._addToErrors(
property,
validation.length,
this._formatMessage(this._validationMessages.wrongLengthMessage, context)
);
}
}
_rangeLength(stringLength, property, validation) {
let minimum = -1,
maximum = Infinity;
// Maximum and Minimum can be objects
if (typeOf(validation.length.minimum) === 'number') {
minimum = validation.length.minimum;
} else if (
typeOf(validation.length.minimum) === 'object' &&
Object.prototype.hasOwnProperty.call(validation.length.minimum, 'value')
) {
minimum = validation.length.minimum.value;
}
if (typeOf(validation.length.maximum) === 'number') {
maximum = validation.length.maximum;
} else if (
typeOf(validation.length.maximum) === 'object' &&
Object.prototype.hasOwnProperty.call(validation.length.maximum, 'value')
) {
maximum = validation.length.maximum.value;
}
if (stringLength < minimum) {
set(this, 'isValidNow', false);
let context = { count: minimum };
if (typeOf(validation.length.minimum) === 'object') {
validation.length.minimum.interpolatedValue = minimum;
}
this._addToErrors(
property,
validation.length.minimum,
this._formatMessage(this._validationMessages.tooShortMessage, context)
);
} else if (stringLength > maximum) {
set(this, 'isValidNow', false);
let context = { count: maximum };
if (typeOf(validation.length.maximum) === 'object') {
validation.length.maximum.interpolatedValue = maximum;
}
this._addToErrors(
property,
validation.length.maximum,
this._formatMessage(this._validationMessages.tooLongMessage, context)
);
}
}
_validateRelations(property, validation) {
if (validation.relations.indexOf('hasMany') !== -1) {
if (get(this, `${property}.content`)) {
get(this, `${property}.content`).forEach((objRelation) => {
if (!objRelation.validate()) {
set(this, 'isValidNow', false);
}
});
}
} else if (validation.relations.indexOf('belongsTo') !== -1) {
if (get(this, `${property}.content`) && !get(this, `${property}.content`).validate()) {
set(this, 'isValidNow', false);
}
}
}
_validateMustContainCapital(property, validation) {
let notContainCapital = String(get(this, property)).match(/(?=.*[A-Z])/) === null,
message = validation.mustContainCapital.message || this._validationMessages.mustContainCapitalMessage;
if (validation.mustContainCapital && notContainCapital) {
set(this, 'isValidNow', false);
this._addToErrors(property, validation, message);
}
}
_validateMustContainLower(property, validation) {
let containsLower = String(get(this, property)).match(/(?=.*[a-z])/) !== null,
message = validation.mustContainLower.message || this._validationMessages.mustContainLowerMessage;
if (validation.mustContainLower && !containsLower) {
set(this, 'isValidNow', false);
this._addToErrors(property, validation, message);
}
}
_validateMustContainNumber(property, validation) {
let containsNumber = String(get(this, property)).match(/(?=.*[0-9])/) !== null,
message = validation.mustContainNumber.message || this._validationMessages.mustContainNumberMessage;
if (validation.mustContainNumber && !containsNumber) {
set(this, 'isValidNow', false);
this._addToErrors(property, validation, message);
}
}
_validateMustContainSpecial(property, validation) {
let regexString = validation.mustContainSpecial.acceptableChars || '-+_!@#$%^&*.,?()',
regex = new RegExp(`(?=.*[${regexString}])`),
containsSpecial = String(get(this, property)).match(regex) !== null,
message = validation.mustContainSpecial.message || this._validationMessages.mustContainSpecialMessage;
if (validation.mustContainSpecial && !containsSpecial) {
set(this, 'isValidNow', false);
let context = { characters: regexString };
this._addToErrors(property, validation, this._formatMessage(message, context));
}
}
/**** Helper methods ****/
_exceptOrOnly(property, validation, options) {
let validateThis = true;
if (isPresent(options.except) && isArray(options.except)) {
validateThis = !this._hasCompositeTag(property, validation, options.except);
}
if (isPresent(options.only) && isArray(options.only)) {
validateThis = this._hasCompositeTag(property, validation, options.only);
}
return validateThis;
}
_hasCompositeTag(property, validation, tags) {
for (const tag of tags) {
if (tag === property) return true;
if (tag.indexOf(':') !== -1) {
const [field, rest = ''] = tag.split(':', 2);
if (field !== property) continue;
const rules = rest.split(',');
for (const rule of rules) {
if (rule === validation) return true;
}
}
}
return false;
}
_getCustomValidator(validation) {
let customValidator = validation;
if (typeOf(validation) === 'object' && Object.prototype.hasOwnProperty.call(validation, 'validation')) {
customValidator = validation.validation;
}
return this._isFunction(customValidator) ? customValidator : false;
}
_getCustomMessage(validationObj, defaultMessage, property) {
if (typeOf(validationObj) === 'object' && Object.prototype.hasOwnProperty.call(validationObj, 'message')) {
if (this._isFunction(validationObj.message)) {
let msg = validationObj.message.call(this, property, get(this, property), this);
return this._isString(msg) ? msg : defaultMessage;
} else {
let context = { value: validationObj.interpolatedValue };
return this._formatMessage(validationObj.message, context);
}
} else {
return defaultMessage;
}
}
_addToErrors(property, validation, defaultMessage) {
let errors = this.validationErrors,
message = this._getCustomMessage(validation, defaultMessage, property),
errorAs = typeOf(validation) === 'object' ? validation.errorAs || property : property;
if (!isArray(errors[errorAs])) {
errors[errorAs] = [];
}
if (this.addErrors) {
errors[errorAs].push([message]);
}
}
// Specific funcs
_isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
_unCamelCase(str) {
return (
str
// insert a space before all caps
.replace(/([A-Z])/g, ' $1')
// uppercase the first character
.replace(/^./, function (str) {
return capitalize(str);
})
);
}
_isFunction(func) {
return isEqual(typeOf(func), 'function');
}
_isString(str) {
return isEqual(typeOf(str), 'string');
}
_includes(enums, value) {
if (enums.includes) {
return enums.includes(value);
} else {
// Support old ember versions
return enums.contains(value);
}
}
_modelRelations() {
// eslint-disable-next-line ember/no-get
if (get(this, '_relationships')) {
return this['_relationships'];
// eslint-disable-next-line ember/no-get
} else if (get(this, '_internalModel._relationships')) {
// eslint-disable-next-line ember/no-get
return get(this, '_internalModel._relationships.initializedRelationships');
// eslint-disable-next-line ember/no-get
} else if (get(this, '_internalModel._recordData._relationships')) {
// eslint-disable-next-line ember/no-get
return get(this, '_internalModel._recordData._relationships.initializedRelationships');
} else {
const relationships = {};
if (this.constructor.eachRelationship) {
this.constructor.eachRelationship((name) => {
relationships[name] = this['relationshipFor'](name);
});
}
return relationships;
}
}
_formatMessage(message, context = {}) {
return message.replace(/\{(\w+)\}/, (s, attr) => context[attr]);
}
};
}
export default coreValidator;