This repository has been archived by the owner on Oct 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
verja.js
284 lines (261 loc) · 7.31 KB
/
verja.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
;
(function(undefined) {
'use strict';
var validators = {
doesNotHave: function(val, config, callback) {
if (!val) return callback(true);
var returnVal = true;
if (Array.isArray(config)) {
config.forEach(function(item) {
if (val.indexOf(item) > -1) returnVal = false;
});
} else {
if (val.indexOf(config) > -1) returnVal = false;
}
return callback(returnVal);
},
//takes lower case string of type for config
email: function(val, config, callback) {
if (!val) return callback(true);
if (typeof val !== 'string') {
return callback(false);
}
var regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (regex.test(val)) {
return callback(true);
}
callback(false);
},
equals: function(val, config, callback) {
if (val === config) {
return callback(true);
}
callback(false);
},
hasLowercaseLetter: function(val, config, callback) {
var regex = /[a-z]/;
if (regex.test(val)) return callback(config);
callback(!config);
},
hasCapitalLetter: function(val, config, callback) {
var regex = /[A-Z]/;
if (regex.test(val)) return callback(config);
callback(!config);
},
hasNumber: function(val, config, callback) {
var regex = /[0-9]/;
if (regex.test(val)) return callback(config);
callback(!config);
},
int: function(val, config, callback) {
if (Math.round(val) === val) {
return callback(true);
}
callback(false);
},
max: function(val, config, callback) {
if (typeof val !== 'number' || !val || val > config) {
return callback(false);
}
callback(true);
},
maxlength: function(val, config, callback) {
try {
if (val.length <= config) {
return callback(true);
} else {
return callback(false);
}
} catch (e) {
return callback(false);
}
},
min: function(val, config, callback) {
if (typeof val !== 'number' || !val || val < config) {
return callback(false);
}
callback(true);
},
minlength: function(val, config, callback) {
if (!val || !val.length || val.length < config) {
return callback(false);
}
callback(true);
},
regex: function(val, config, callback) {
if (val.search(config) > -1) {
return callback(true);
}
callback(false);
},
required: function(val, config, callback) {
if (config) {
if (!val || typeof val === undefined) {
return callback(false);
}
}
callback(true);
},
type: function(val, config, callback) {
var valtype = Object.prototype.toString.call(val);
valtype = valtype.substr(8, valtype.length - 9).toLowerCase();
if (valtype === config) {
return callback(true);
}
callback(false, 'type');
},
url: function(val, config, callback) {
var regex = /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)/;
if (regex.test(val) || !val) {
return callback(true);
}
callback(false);
}
};
function addValidator(name, func) {
validators[name] = func;
}
function validate(object, schema, callback) {
//create a schema and accumulate all of its validators
var s = new Schema(schema, callback);
//accumulate all the validation functions we need to run over the object
s.accumulateValidators(object);
//run them all
s.run();
}
function Schema(schema, userCallback) {
this.schema = schema;
this.errors = {};
this.validationStatus = {
totalValidators: 0,
totalValidated: 0,
errorTotal: 0,
};
this.validateFuncs = [];
this.userCallback = userCallback;
}
Schema.prototype.accumulateValidators = function(object, schema, errors) {
var self = this;
if (!schema) {
schema = self.schema;
}
if (!errors) {
errors = self.errors;
}
if (schema instanceof Field) {
// if array with itemSchema, we need to add a validation function for each item in the array
if (schema.itemSchema && Array.isArray(object)) {
object.forEach(function(arrayValue, index) {
self.addPropertyToErrors(errors, index);
self.accumulateValidators(object[index], schema.itemSchema, errors[index]);
});
}
//Add a validator for each one declared on the Field
Object.keys(schema).forEach(function(validatorName) {
if (validators[validatorName]) {
self.addValidationFunction(object, schema, errors, validatorName);
} else {
//handle non validator keys here
}
});
}
//otherwise go through the keys on the schema and recurse
else if (schema instanceof Object && object instanceof Object) {
Object.keys(schema).forEach(function(property) {
self.addPropertyToErrors(errors, property);
self.accumulateValidators(object[property], schema[property], errors[property]);
});
} else {
// this should never happen, if it does, we aren't handling an object/schema construction error properly
throw new Error('Internal Validation error for ', object, schema, errors);
}
};
Schema.prototype.addValidationFunction = function(object, schema, errors, validatorName) {
var self = this;
self.validateFuncs.push(function() {
var validatorCallback = self.generateValidatorCallback(object, schema, errors, validatorName);
//call the validator
validators[validatorName](object, schema[validatorName], validatorCallback);
});
self.validationStatus.totalValidators++;
};
//generates the internal callback for the validator
Schema.prototype.generateValidatorCallback = function(object, schema, errors, validatorName) {
var self = this;
return function(valid) {
//set the error if it was invalid
if (!valid) {
errors[validatorName] = true;
self.validationStatus.errorTotal++;
}
self.validationStatus.totalValidated++;
self.checkValidationComplete();
};
};
Schema.prototype.addPropertyToErrors = function(errors, property) {
if (!errors[property]) {
errors[property] = {};
}
};
Schema.prototype.run = function() {
this.validateFuncs.forEach(function(func) {
func();
});
};
Schema.prototype.checkValidationComplete = function() {
var self = this;
if (self.validationStatus.totalValidated === self.validationStatus.totalValidators) {
if (!self.validationStatus.errorTotal) {
return self.userCallback(null);
}
self.userCallback(self.errors);
}
};
function Field(props) {
for (var prop in props) {
this[prop] = props[prop];
}
}
/*
Recursively removes empty objects from an object of arbitrary depth.
Copies the object first to not modify the original
ex: turns {
prop: {},
prop2: {some: {}, thing: 5}
}
into
{
prop2: {thing: 5}
}
*/
function strip(obj, isRecurse) {
//make a copy of the object the first time so we dont modify the original
if (!isRecurse) { obj = new Field(obj); }
//go through each property on the object
Object.keys(obj).forEach(function(key) {
//if its an object and has no properties
if (obj[key] instanceof Object && !Object.keys(obj[key]).length) {
//delete it
delete obj[key];
//call the whole thing again so we can strip the parent if necessary
obj = strip(obj, true);
} else if (obj[key] instanceof Object) {
//otherwise recurse
obj[key] = strip(obj[key], true);
}
});
return obj;
}
var exports = {
addValidator: addValidator,
validate: validate,
Field: Field,
validators: validators,
strip: strip
};
if (typeof window !== 'undefined') {
window.verja = window.verja || exports;
} else if (module) {
module.exports = exports;
}
})();