forked from thosakwe/feathers-validator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
400 lines (365 loc) · 13.3 KB
/
index.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
const moment = require('moment');
//Polyfills, if you're not using ES6.
if (!String.prototype.startsWith) {
String.prototype.startsWith = function (searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
};
}
function validatorFunctionFor(criterion_, params_, data) {
var generateFunction = function (criterion, params) {
if (criterion === 'required')
return generateRequiredValidatorFunction();
else if (criterion === 'alpha_dash')
return generateAlphaDashValidatorFunction();
else if (criterion === 'alpha_num')
return generateAlphaNumValidatorFunction();
else if (criterion === 'boolean')
return generateBooleanValidatorFunction();
else if (criterion === 'confirmed')
return generateConfirmedValidatorFunction(params, data);
else if (criterion === 'email')
return generateEmailValidatorFunction();
else if (criterion === 'integer')
return generateIntegerValidatorFunction();
else if (criterion === 'max')
return generateMaxValidatorFunction(params);
else if (criterion === 'min')
return generateMinValidatorFunction(params);
else if (criterion === 'negative')
return generateNegativeValidatorFunction();
else if (criterion === 'numeric')
return generateNumericValidatorFunction();
else if (criterion === 'positive')
return generatePositiveValidatorFunction();
else if (criterion === 'regex')
return generateRegexValidatorFunction(params);
else if (criterion === 'date')
return generateDateValidatorFunction(params);
else if(criterion === 'enum')
return generateEnumValidatorFunction(params);
return null; //Fallthrough
}
//If parameters were not given already
if (params_ == undefined) {
//Parse criteria with colons
var splitByPipe = criterion_.split(':');
if (splitByPipe.length > 1) {
var criterion = splitByPipe[0];
return generateFunction(criterion, splitByPipe[1].split(','));
} else return generateFunction(criterion_);
} else return generateFunction(criterion_, params_);
}
//Validator generators.
//If you want to add a new one, include a generator function here.
//The generator must return a function(key, value).
//This function in turn must return either:
//{valid: true}
//OR
//{valid: false, error: 'Your error message here'}
//Otherwise, the validator will crash.
function generateAlphaDashValidatorFunction() {
"use strict";
return function (key, value) {
var regex = /^[A-Za-z0-9_-]+$/;
if (regex.test(value)) return {valid: true};
else return {
valid: false,
error: 'The ' + key + ' field must only contain letters, numbers, dashes or underscores.'
}
}
}
function generateAlphaNumValidatorFunction() {
"use strict";
return function (key, value) {
var regex = /^[A-Za-z0-9]+$/;
if (regex.test(value)) return {valid: true};
else return {
valid: false,
error: 'The ' + key + ' field must only contain letters and numbers.'
}
}
}
function generateBooleanValidatorFunction() {
"use strict";
return function (key, value) {
if ((value == 0 || value == 1) || (typeof value == "string" && (value =='true' || value =='false')) || (typeof value == "boolean")) return {valid: true};
else return {
valid: false,
error: 'The ' + key + ' field must have a value of true or false.'
}
}
}
function generateConfirmedValidatorFunction(params, data) {
"use strict";
return function (key, value) {
if (value) {
if (data[key] === data[key + "_confirmation"]) return {valid: true};
else return {
valid: false,
error: 'The two ' + key + ' fields must match.'
}
} else return {
valid: false,
error: 'The ' + key + ' field must be present, and it must be confirmed.'
}
}
}
function generateEmailValidatorFunction() {
"use strict";
return function (key, value) {
//Check for RFC 5322 compliance.
var regex = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
if (regex.test(value)) return {valid: true};
else return {
valid: false,
error: 'The ' + key + ' field must be a valid e-mail address.'
}
}
}
function generateIntegerValidatorFunction() {
return function (key, value) {
var testNumeric = generateNumericValidatorFunction()(key, value);
if (testNumeric.valid) {
if (value % 1 === 0) {
return {valid: true}
} else return {
valid: false,
error: 'The ' + key + ' field must be a positive or negative integer.'
}
} else return testNumeric;
}
}
function generateMinValidatorFunction(params) {
return function (key, value) {
try {
if (typeof value === 'number' || !isNaN(value) || value == undefined) {
if ((value + '').length >= params[0]) return {valid: true};
else return {
valid: false,
error: 'The size of the ' + key + ' field must be greater than or equal to ' + params[0] + '.'
}
} else if (typeof value === 'string') {
if (value.length >= params[0]) return {valid: true};
else return {
valid: false,
error: 'The size of the ' + key + ' field cannot be less than ' + params[0] + ' characters long.'
}
}
} catch (error) {
return {
valid: false,
error: 'Validation error: ' + error.message
}
}
}
}
function generateMaxValidatorFunction(params) {
return function (key, value) {
try {
if (typeof value === 'number' || !isNaN(value) || value == undefined) {
if ((value + '').length <= params[0]) return {valid: true};
else return {
valid: false,
error: 'The size of the ' + key + ' field must be less than or equal to ' + params[0] + '.'
}
} else if (typeof value === 'string') {
if (value.length <= params[0]) return {valid: true};
else return {
valid: false,
error: 'The size of the ' + key + ' field cannot be more than ' + params[0] + ' characters long.'
}
}
} catch (error) {
return {
valid: false,
error: 'Validation error: ' + error.message
}
}
}
}
function generateNegativeValidatorFunction() {
return function (key, value) {
var testInteger = generateIntegerValidatorFunction()(key, value);
if (testInteger.valid) {
if (value < 0) return {valid: true}
else return {
valid: false,
error: 'The ' + key + ' field must be a negative integer.'
}
} else return testInteger;
}
}
function generateNumericValidatorFunction() {
return function (key, value) {
if (typeof value === 'number' || !isNaN(value)) {
return {valid: true}
} else return {
valid: false,
error: 'The ' + key + ' field must be a numeric value.'
}
};
}
function generatePositiveValidatorFunction() {
return function (key, value) {
var testInteger = generateIntegerValidatorFunction()(key, value);
if (testInteger.valid) {
if (value > 0) return {valid: true}
else return {
valid: false,
error: 'The ' + key + ' field must be a positive integer.'
}
} else return testInteger;
}
}
function generateRegexValidatorFunction(params) {
"use strict";
return function (key, value) {
var regex = new RegExp("^" + params[0] + "$");
if (regex.test(value)) return {valid: true};
else return {
valid: false,
error: 'The ' + key + ' field must match this regular expression: \'' + params[0] + "'."
}
}
}
function generateDateValidatorFunction(params) {
return function (key, value) {
var dateFormat = params[0];
if(moment(value, dateFormat, true).isValid()) {
return { valid: true };
} else {
return {
valid: false,
error: 'The ' + key + ' field is invalid.'
};
}
};
}
function generateEnumValidatorFunction(params) {
return function (key, value) {
if(params.indexOf(value) === -1) {
return {
valid: false,
error: 'The ' + key + ' field is invalid.'
};
} else {
return { valid: true };
}
};
}
function generateRequiredValidatorFunction() {
return function (key, value) {
if (value || (typeof value == "boolean")) return {valid: true}
else return {
valid: false,
error: 'The ' + key + ' field is required.'
}
}
}
//Exports a class.
//This class looks something like this:
//{
// errors: [],
// validatorFunctionFor: function(criterion_, params_)
//}
//Simply instantiate it with your form data and validation rules.
//The form data and validation rules should be objects.
//The errors() method returns a string array containing any validation errors encountered.
//Example:
/*
var Validator = require('feathers-validator');
var validator = new Validator(data, {
username: 'required|max:255',
password: 'required|min:6',
email: 'required|email',
add_to_mailing_list: 'required|boolean'
});
console.log('There were ' + validator.errors().length + ' errors in your input.');
*/
//RULES:
//Can take any of the following forms:
//1.
// A string, with rules separated by pipes (|).
// Rule parameters are denoted by a colon (:) and separated by commas (,).
// Example: 'required|min:6|rule:foo,bar'
//2.
// An object, where every rule is an object.
// Rule parameters take the form of arrays.
// Example:
// {
// required: true,
// min: 6,
// rule: ['foo', 'bar']
// }
module.exports = function (data, rules, messages) {
messages = messages || {};
var errors = {};
//Yay
var keys = Object.keys(rules);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var rule = rules[key];
if (typeof rule === 'string') {
// i.e. 'min:6'
var stringCriteria = rule.split('|');
stringCriteria.forEach(function (criterion) {
if (data[key] || rules[key].indexOf('required') != -1) {
var assert = validatorFunctionFor(criterion, null, data);
if (assert) {
var result = assert(key, data[key]);
if (!result.valid) {
var dataVal = data[key] || "";
addError(key, getErrorMessage(key, criterion, result.error), criterion, "ValidatorError", dataVal);
}
} else throw new Error('Unrecognized criterion: "' + criterion + '"');
}
});
} else if (typeof rule === 'object') {
// i.e. { min: 6 }
var objectCriteria = Object.keys(rule);
objectCriteria.forEach(function (criterion) {
if (data[key] || rules[key].indexOf('required') != -1) {
var assert = validatorFunctionFor(criterion, typeof rule[criterion] === 'object' ? rule[criterion] : [rule[criterion]], data);
if (assert) {
var result = assert(key, data[key]);
if (!result.valid) {
var dataVal = data[key] || "";
addError(key, getErrorMessage(key, criterion, result.error), criterion, "ValidatorError", dataVal);
}
} else throw new Error('Unrecognized criterion: "' + criterion + '"');
}
});
}
}
/***
Format to mongoose type error
"label": {
"message": "Path `label` is required.",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "label",
"value": ""
},
"kind": "required",
"path": "label",
"value": ""
}
*/
function addError(key, message, kind, name, value) {
if(!errors[key]) {
errors[key] = { message : message, name : name, properties: { type : kind, message: message, path: key, value: value }, kind:kind, path:key, value:value };
}
};
function getErrorMessage(key, criterion, defaultMessage) {
criterion = criterion.split(':')[0];
var messageKey = key + '.' + criterion;
return (!messages[messageKey]) ? defaultMessage : messages[messageKey];
};
this.errors = function () {
"use strict";
return errors;
}
};