validator-extras.js
2.19 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
'use strict';
const _ = require('lodash');
const validator = _.cloneDeep(require('validator'));
const extensions = {
extend(name, fn) {
this[name] = fn;
return this;
},
notEmpty(str) {
return !str.match(/^[\s\t\r\n]*$/);
},
len(str, min, max) {
return this.isLength(str, min, max);
},
isUrl(str) {
return this.isURL(str);
},
isIPv6(str) {
return this.isIP(str, 6);
},
isIPv4(str) {
return this.isIP(str, 4);
},
notIn(str, values) {
return !this.isIn(str, values);
},
regex(str, pattern, modifiers) {
str += '';
if (Object.prototype.toString.call(pattern).slice(8, -1) !== 'RegExp') {
pattern = new RegExp(pattern, modifiers);
}
return str.match(pattern);
},
notRegex(str, pattern, modifiers) {
return !this.regex(str, pattern, modifiers);
},
isDecimal(str) {
return str !== '' && !!str.match(/^(?:-?(?:[0-9]+))?(?:\.[0-9]*)?(?:[eE][\+\-]?(?:[0-9]+))?$/);
},
min(str, val) {
const number = parseFloat(str);
return isNaN(number) || number >= val;
},
max(str, val) {
const number = parseFloat(str);
return isNaN(number) || number <= val;
},
not(str, pattern, modifiers) {
return this.notRegex(str, pattern, modifiers);
},
contains(str, elem) {
return str.indexOf(elem) >= 0 && !!elem;
},
notContains(str, elem) {
return !this.contains(str, elem);
},
is(str, pattern, modifiers) {
return this.regex(str, pattern, modifiers);
}
};
exports.extensions = extensions;
function extendModelValidations(modelInstance) {
const extensions = {
isImmutable(str, param, field) {
return (modelInstance.isNewRecord || modelInstance.dataValues[field] === modelInstance._previousDataValues[field]);
}
};
_.forEach(extensions, (extend, key) => {
validator[key] = extend;
});
}
exports.extendModelValidations = extendModelValidations;
// Deprecate this.
validator.notNull = function() {
throw new Error('Warning "notNull" validation has been deprecated in favor of Schema based "allowNull"');
};
// https://github.com/chriso/validator.js/blob/1.5.0/lib/validators.js
_.forEach(extensions, (extend, key) => {
validator[key] = extend;
});
exports.validator = validator;