-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
496 lines (432 loc) · 15.2 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
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
/**
* Created by sabyasachi on 07/07/18.
*/
/**
* Created by sabyasachi on 14/09/17.
*/
var sprintf = require("sprintf-js").sprintf, vsprintf = require("sprintf-js").vsprintf;
/**
* TO - DO
* 1. SAME : same as another field name , or same as given variable
* 2. Exists IN DB
*
*
*/
/**
* CONSTANTS
* DEFAULT ERROR MESSAGE PLACE HOLDERS
* @type {string}
*/
const DEFAULT_ERROR_MESSAGES = {
"email": "%s is invalid",
"mobile" : "%s is not a mobile",
"mobile_with_country_code" : "%s is not a valid mobile with country code",
"alphabets" : "%1$s should contain only alphabets",
"string" : "%1$s should contain only alphabets and space",
"number" : "%1$s should be a number",
"nospecial" : "%1$s shouldn't contain special characters",
"required" : "%s is required",
"max" : "%1$s shouldn't be more than %2$s",
"min" : "%1$s shouldn't be less than %2$s",
"len" : "%1$s should be exactly %2$s characters long",
"in_string" : "%1$s should be one of the value from : %2$s ",
};
/**
* VALIDATOR - CONSTRUCTOR
* @param inputData
* @param rules
* @param messages
* @constructor
*/
function Validator(inputData, rules, messages) {
this.inputs = inputData;
this.rules = rules;
this.customMessages = messages;
this.errorMessages = {};
this.allErrorMessages = {};
this.valid = true;
};
/**
* VALIDATE METHOD
* @returns {Validator}
*/
Validator.prototype.validate = function() {
Object.keys(this.rules).forEach(function(field) {
var fieldRuleStr = this.rules[field].trim();
var fieldRules = fieldRuleStr.split('|');
fieldRules.forEach( function(aRule) {
if(aRule == undefined || aRule == null || aRule.trim().length <= 0){
throw new Error('Invalid validation rule type provided : ' + aRule);
}
var aRule = aRule.trim();
if (aRule === "email") {
// validate email
if (!this.email(this.inputs[field])) {
this.setError(field, aRule);
}
} else if (aRule === "mobile") {
// validate mobile
if (!this.mobile(this.inputs[field])) {
this.setError(field, aRule);
}
}
else if (aRule === "mobile_with_country_code") {
// validate mobile_with_country_code
if (!this.mobile_with_country_code(this.inputs[field])) {
this.setError(field, aRule);
}
}
else if (aRule === "alphabets") {
// validate alphabets
if (!this.alphabets(this.inputs[field])) {
this.setError(field, aRule);
}
}
else if (aRule === "string") {
// validate alphabets
if (!this.string(this.inputs[field])) {
this.setError(field, aRule);
}
}
else if (aRule === "number") {
// validate number
if (!this.number(this.inputs[field])) {
this.setError(field, aRule);
}
}
else if (aRule === "nospecial") {
// validate nospecial
if (!this.nospecial(this.inputs[field])) {
this.setError(field, aRule);
}
}
else if (aRule === "required") {
// validate mobile
if (!this.required(this.inputs, field)) {
this.setError(field, aRule);
}
}
else if (aRule.substring(0, 3) === "min") {
// validate min
var defaultMinValue = -1;
var minSplits = aRule.split(':');
if (minSplits.length === 2) {
if (!isNaN(minSplits[1])) {
defaultMinValue = Number(minSplits[1]);
}
}
if (defaultMinValue < 0) {
throw Error('invalid way to use min validator');
}
if (!this.min(this.inputs[field], defaultMinValue)) {
this.setError(field, aRule);
}
}
else if (aRule.substring(0, 3) === "max") {
// validate min
var defaultValue = -1;
var maxSplits = aRule.split(':');
if (maxSplits.length === 2) {
if (!isNaN(maxSplits[1])) {
defaultValue = Number(maxSplits[1]);
}
}
if (defaultValue < 0) {
throw Error('invalid way to use max validator');
}
if (!this.max(this.inputs[field], defaultValue)) {
this.setError(field, aRule);
}
}
else if (aRule.substring(0, 3) === "min") {
// validate min
var defaultValue = -1;
var maxSplits = aRule.split(':');
if (maxSplits.length === 2) {
if (!isNaN(maxSplits[1])) {
defaultValue = Number(maxSplits[1]);
}
}
if (defaultValue < 0) {
throw Error('invalid way to use min validator');
}
if (!this.min(this.inputs[field], defaultValue)) {
this.setError(field, aRule);
}
}
else if (aRule.substring(0, 3) === "len") {
// validate len
var defaultValue = -1;
var maxSplits = aRule.split(':');
if (maxSplits.length === 2) {
if (!isNaN(maxSplits[1])) {
defaultValue = Number(maxSplits[1]);
}
}
if (defaultValue < 0) {
throw Error('invalid way to use len validator');
}
if (!this.len(this.inputs[field], defaultValue)) {
this.setError(field, aRule);
}
}
else if (aRule.substring(0, 9) === "in_string") {
// validate in_string
var inStringSplits = aRule.split(':');
var strArr = [];
if(inStringSplits.length === 2){
strArr = inStringSplits[1].trim().split(',').map(Function.prototype.call, String.prototype.trim);
}else{
throw Error('invalid way to use in_string validator');
}
if(strArr.length <= 0){
throw Error('invalid way to use in_string validator');
}
if (!this.in_string(this.inputs[field], strArr)) {
this.setError(field, aRule);
}
}
else{
throw new Error('Undefined validation rule type : ' + aRule);
}
}.bind(this) );
}.bind(this) );
// filter out error messages
return this;
};
/**
* SET ERROR
* @param field
* @param rule
*/
Validator.prototype.setError = function(field, rule) {
this.valid = false;
// check if rule is something like min:5 , max:5, unique:email
var sanitizedRuleStr = this.sanitizeRule(rule);
var paramsArr = [field]; // default paramArr contains field name
paramsArr = paramsArr.concat(this.getRuleParams(rule));
// get the default error
var e = {}; e[sanitizedRuleStr] = vsprintf(DEFAULT_ERROR_MESSAGES[sanitizedRuleStr], paramsArr);
// replace with custom error object if required
if(this.customMessages.hasOwnProperty(field) && this.customMessages[field] !== null && this.customMessages[field] !== undefined ) {
var customFieldErrObj = this.customMessages[field];
if(customFieldErrObj.hasOwnProperty(sanitizedRuleStr) && customFieldErrObj[sanitizedRuleStr] !== null && customFieldErrObj[sanitizedRuleStr] !== undefined && customFieldErrObj[sanitizedRuleStr].trim().length > 0 ){
e[sanitizedRuleStr] = customFieldErrObj[sanitizedRuleStr].trim();
}
}
// add property
if( this.errorMessages.hasOwnProperty(field) && this.errorMessages[field] !== undefined && this.errorMessages[field] !== null ){
this.errorMessages[field][sanitizedRuleStr] = e[sanitizedRuleStr];
}else{
this.errorMessages[field] = e;
}
};
/**
* GET ALL ERRORS
* Returns all errors and with field name as key and error messages as array of strings
* {
* email : [
* "Email is required",
* "Invalid Email"
* ],
* password : [
* "Password is required",
* "Password must be same as confirm password"
* ]
* }
* @param field
* @param rule
*/
Validator.prototype.getAllErrorsMessages = function() {
Object.keys(this.errorMessages).forEach(function(aFieldName) {
this.allErrorMessages[aFieldName] = this.getAllErrorMessagesFor(aFieldName);
}.bind(this) );
return this.allErrorMessages;
};
/**
* GET ALL ERROR MESSAGES FOR A SPECIFIC FIELD
* @param fieldName
* @returns {Array}
*/
Validator.prototype.getAllErrorMessagesFor = function(fieldName) {
var retErrArr = [];
if(this.errorMessages.hasOwnProperty(fieldName) && this.errorMessages[fieldName] !== null && this.errorMessages[fieldName] !== undefined ){
var aErrorMessageObj = this.errorMessages[fieldName];
var keysOfErrMsgObj = Object.keys(aErrorMessageObj);
for(var x = 0; x < keysOfErrMsgObj.length; x++){
var aRuleKey = keysOfErrMsgObj[x];
var errorStr = aErrorMessageObj[aRuleKey];
if(errorStr !== undefined && errorStr !== null && errorStr.trim().length > 0 ) {
retErrArr.push(errorStr);
}
}
}
return retErrArr;
};
/**
* GET ALL ERROR MESSAGES FOR A SPECIFIC FIELD
* @param fieldName
* @returns {Array}
*/
Validator.prototype.getFirstErrorMessageFor = function(fieldName) {
var retErr = "";
if(this.errorMessages.hasOwnProperty(fieldName) && this.errorMessages[fieldName] !== null && this.errorMessages[fieldName] !== undefined ){
var aErrorMessageObj = this.errorMessages[fieldName];
var keysOfErrMsgObj = Object.keys(aErrorMessageObj);
for(var x = 0; x < keysOfErrMsgObj.length; x++){
var aRuleKey = keysOfErrMsgObj[x];
var errorStr = aErrorMessageObj[aRuleKey];
if(errorStr !== undefined && errorStr !== null && errorStr.trim().length > 0 ) {
retErr = errorStr;
break;
}
}
}
return retErr;
};
/**
* HAS ERROR
* @param fieldName
* @returns {boolean}
*/
Validator.prototype.hasError = function(fieldName) {
var hasError = false;
if(this.errorMessages.hasOwnProperty(fieldName) && this.errorMessages[fieldName] !== null && this.errorMessages[fieldName] !== undefined ){
hasError = true;
}
return hasError;
};
/**
* SANITIZE RULE STRING
* IF ruleStrInput is : max:5, then it returns max
* IF ruleStrInput is : unique:email, then it returns unique
* @param ruleStrInput
* @returns {SchemaType|string|*}
*/
Validator.prototype.sanitizeRule = function(ruleStrInput) {
var fieldRuleSplitValues = ruleStrInput.trim().split(':');
/*if(fieldRuleSplitValues.length > 1){
return fieldRuleSplitValues[0];
}*/
return fieldRuleSplitValues[0].trim();
};
/**
* GET PARAMS OF THE RULE
* e.g ruleStrInput = min:5, then it returns ['5']
* ruleStrInput = unique:email:email_id, then it returns ['email', 'email_id']
* @param ruleStrInput
* @returns {Array}
*/
Validator.prototype.getRuleParams = function(ruleStrInput) {
var retParams = [];
var fieldRuleSplitValuesArr = ruleStrInput.trim().split(':');
if(fieldRuleSplitValuesArr.length > 1){
for (var x=0; x < fieldRuleSplitValuesArr.length; x++){
var aSplitValue = fieldRuleSplitValuesArr[x].trim();
if(DEFAULT_ERROR_MESSAGES.hasOwnProperty(aSplitValue) && DEFAULT_ERROR_MESSAGES[aSplitValue] !== null && DEFAULT_ERROR_MESSAGES[aSplitValue] !== undefined ){
// skip this one
// its a rule, not a param
}else{
retParams.push(aSplitValue);
}
}
}
return retParams;
};
// email
Validator.prototype.email = function(emailStr) {
if(emailStr != undefined && emailStr != null && emailStr.trim().length > 0){
let pattern =/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
return pattern.test(emailStr);
}
return false;
};
// mobile
Validator.prototype.mobile = function(mobileStr) {
if(mobileStr != undefined && mobileStr != null && mobileStr.trim().length > 0){
let pattern = /^\d{10}$/;
return pattern.test(mobileStr);
}
return false;
};
// mobile
Validator.prototype.mobile_with_country_code = function(mobileStr) {
if(mobileStr != undefined && mobileStr != null && mobileStr.length === 13){
var countryCode = mobileStr.substring(0, 3);
if(countryCode !== "+91"){
return false
}else{
var mobile = mobileStr.substring(3);
let pattern = /^\d{10}$/;
return pattern.test(mobile);
}
}else{
return false;
}
};
// alphabet
Validator.prototype.alphabets = function(alphabetStr) {
if(alphabetStr != undefined && alphabetStr != null && alphabetStr.trim().length > 0){
let pattern = /^[a-zA-Z]+$/;
return pattern.test(alphabetStr);
}
return false;
};
// string
Validator.prototype.string = function(inputStr) {
if(inputStr != undefined && inputStr != null && inputStr.trim().length > 0){
let pattern = /^[a-zA-Z ]*$/;
return pattern.test(inputStr);
}
return false;
};
// number
Validator.prototype.number = function(numberStr) {
if(numberStr != undefined && numberStr != null && numberStr.trim().length > 0){
let pattern = /^\d+$/;
return pattern.test(numberStr);
}
return false;
};
// nospecial
Validator.prototype.nospecial = function(inputStr) {
if(inputStr != undefined && inputStr != null && inputStr.trim().length > 0){
let pattern = /[ !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
return !pattern.test(inputStr);
}
return false;
};
// required
Validator.prototype.required = function(input, field) {
return input.hasOwnProperty(field) && input[field].trim().length > 0;
};
// min
Validator.prototype.min = function(input, min) {
if(input != undefined && input != null && input.trim().length > 0){
return input.trim().length >= min;
}
return false;
};
// max
Validator.prototype.max = function(input, max) {
if(input != undefined && input != null && input.trim().length > 0){
return input.trim().length <= max;
}
return false;
};
// len
Validator.prototype.len = function(input, max) {
if(input != undefined && input != null && input.trim().length > 0){
return input.trim().length === max;
}
return false;
};
// in_string
Validator.prototype.in_string = function(input, strArr) {
if(input != undefined && input != null && input.trim().length > 0){
return strArr.indexOf(input.trim()) > -1;
}
return false;
};
// Export
module.exports = Validator;