-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
validator.js
340 lines (283 loc) · 7.97 KB
/
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
'use strict';
// Dependencies
var utils = require('./utils.js');
var extend = utils.extend;
// Implementation
var Field = require('./field.js');
module.exports = Validator;
exports.Field = Field;
/**
* Create validator. Options could have properties `forceAsync`, `skipMissed` and `rules`.
* @memberof module:helpers
* @param {Object} options
* @constructor
*/
function Validator (options) {
options = options || {};
this.hasError = false;
this.forceAsync = this.forceAsync || options.forceAsync;
this.skipMissed = this.skipMissed || options.skipMissed;
this.execRules = this.execRules || options.execRules;
this.rules = extend(Object.create(this.rules), options.rules);
var reporter = this.reporter || options.reporter;
if (typeof reporter === 'function') {
reporter = new reporter(this);
}
this.reporter = reporter;
this.onInit();
}
/**
* Make validation async even if no async rules are used.
* @type {boolean}
*/
Validator.prototype.forceAsync = false;
/**
* Don't throw error if rule is missed
* @type {boolean}
*/
Validator.prototype.skipMissed = false;
/**
* If rule value is function run it to get value
* @type {boolean}
*/
Validator.prototype.execRules = true;
/**
* Issue reporter. Convert issues.
* @type {Reporter}
*/
Validator.prototype.reporter = null;
/**
* Check whether rule exists.
* @param {string} name
* @return {boolean}
*/
Validator.prototype.hasRule = function (name) {
return name in this.rules;
};
/**
* Get rule descriptor.
* @param {string} name
* @return {*}
*/
Validator.prototype.getRule = function (name) {
if (name in this.rules === false) {
throw new Error('Rule "' + name + '" is not defined');
}
return this.rules[name];
};
/**
* Validate values with specified rules set
* @param {*} value
* @param {object} rules Set of rules
* @param {function} callback Result callback (err:Error,report:Array,output:*)=
* @return {object} report
* @throws {err} If finish err parameter is true
* @throws {Error} If callback, async and finished are not valid
* @todo debug this function and adjust callback function parameter
*/
Validator.prototype.validate = function (value, rules, callback) {
var self = this;
var field = this.createField(null, value, rules);
var async, finished, report;
report = {};
function finish (err, issues, output) {
finished = true;
report.isValid = !issues.length;
if (self.reporter) {
issues = self.reporter.convert(issues, rules);
}
report.isAsync = async;
report.issues = issues;
report.rules = rules;
report.value = output;
if (!callback) {
if (err) {
throw err;
} else if (async) {
throw new Error('Async validation without callback');
}
return;
}
if (async || !callback || !self.forceAsync) {
self.onEnd();
callback.call(self, err, report, output);
} else {
setTimeout(function () {
self.onEnd();
callback.call(self, err, report, output);
}, 1);
}
}
async = false;
field.validate(finish);
async = true;
if (!callback && !finished) {
throw new Error('Validation not finished');
}
return report;
};
/**
* Validator field constructor
* @type {Field}
*/
Validator.prototype.Field = Field;
/**
* Create field instance
* @param {string|string[]} path Field path
* @param {*} value Validated value
* @param {object} rules Rule set
* @param {*=} thisArg This reference for Validation methods. Optional
* @return {Validator.Field}
*/
Validator.prototype.createField = function (path, value, rules, thisArg) {
return new this.Field(this, path, value, rules, thisArg);
};
/**
* Set of validator rule descriptors
* @type {{}}
*/
Validator.prototype.rules = {};
// Internal event handlers
Validator.prototype.onInit = function () {};
Validator.prototype.onError = function (field, err) {};
Validator.prototype.onValid = function (field) {};
Validator.prototype.onInvalid = function (field) {};
Validator.prototype.onEnd = function () {};
// Constructor methods
/**
* Add validation rule descriptor to validator rule set.
* @param {string} name Validator name
* @param {{validate:function,filter:function}} descriptor Validator descriptor object
*/
Validator.addRule = function (name, descriptor) {
if (typeof descriptor !== 'object') {
throw new Error('Rule descriptor should be an object');
}
var self = this;
this.prototype.rules[name] = descriptor;
if (descriptor.hasOwnProperty('aliases')) {
descriptor.aliases.forEach(function (alias) {
self.addAlias(alias, name);
});
}
};
/**
* Add rule alias
* @param {string} name
* @param {string} origin
*/
Validator.addAlias = function (name, origin) {
Object.defineProperty(this.prototype.rules, name, {
get: function () {
return this[origin];
}
});
};
/**
* Add extra property to Field. It could be
* @param name
* @param value
*/
Validator.fieldProperty = function (name, value) {
this.prototype.Field.prototype[name] = value;
};
/**
* Validator instance options for fast initialization in method validate.
* @type {{forceAsync: boolean, skipMissed: boolean}}
*/
Validator.options = {
forceAsync: false,
skipMissed: false,
execRules: true,
reporter: null
};
/**
* Validate with fast initialization. Use `options` property for constructor instance;
* @param {*} value Validated value
* @param {object} rules Set of rules
* @param {object} customRules Customized rule set. Optional
* @param {function} callback assign customRules if it is a function
* @return {instance} instance
*/
Validator.validate = function (value, rules, customRules, callback) {
if (typeof customRules === 'function') {
callback = customRules;
customRules = {};
}
var instance = new this(extend({}, this.options, {
rules: customRules
}));
return instance.validate(value, rules, callback);
};
// Default rules
Validator.addRule('defaults', {
description: 'Set default value if passed value is undefined',
filter: function (accept, value) {
if (typeof value === 'undefined') {
return accept;
} else {
return value;
}
}
});
Validator.addRule('type', {
description: 'Check value type',
validate: function (accept, value) {
return typeof value === accept;
}
});
Validator.addRule('equal', {
description: 'Check if value equals acceptable value',
validate: function (accept, value) {
return value === accept;
}
});
Validator.addRule('notEqual', {
description: 'Check if value not equals acceptable value',
validate: function (accept, value) {
return typeof value !== accept;
}
});
Validator.addRule('greater', {
description: 'Check if value is greater then acceptable value',
aliases: ['>', 'gt'],
validate: function (accept, value) {
return typeof value > accept;
}
});
Validator.addRule('greaterOrEqual', {
description: 'Check if value is greater then or equal acceptable value',
aliases: ['>=', 'gte'],
validate: function (accept, value) {
return typeof value >= accept;
}
});
Validator.addRule('less', {
description: 'Check if value is less then acceptable value',
aliases: ['<', 'lt'],
validate: function (accept, value) {
return typeof value < accept;
}
});
Validator.addRule('lessOrEqual', {
description: 'Check if value is less then or equal acceptable value',
aliases: ['<=', 'lte'],
validate: function (accept, value) {
return typeof value <= accept;
}
});
Validator.fieldProperty('isObject', function () {
return this.value !== null && typeof this.value === 'object';
});
Validator.fieldProperty('isObjectInstance', function () {
return this.value && typeof this.value === 'object' && this.value.constructor === Object;
});
Validator.fieldProperty('isDefault', function () {
return this.value === this.rules.defaults;
});
Validator.fieldProperty('isUndefined', function () {
return typeof this.value === 'undefined';
});
Validator.fieldProperty('isEmpty', function () {
return typeof this.value === 'undefined' || this.value === null || this.value === '';
});