-
Notifications
You must be signed in to change notification settings - Fork 1
/
ThatValidator.js
545 lines (414 loc) · 15.4 KB
/
ThatValidator.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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
/**====-----==============================================
|| /
|
| ThatValidator.js
|
| Site: http://jondum.github.com/ThatValidator
| Author: Jonathan Dumaine
| Version: 1.0.0
| License: MIT
|
|| \
/**====-----=============================================*/
(function(window, document) {
"use strict";
var noop = function() {};
var defaultConfig = {
completed: noop,
onFocus: noop,
onBlur: noop,
onKeyPress: noop,
debounceDelay: 1000,
fields: { }
};
ThatValidator.prototype = {
/* Used to stop multiple calls to onComplete if the state hasn't changed */
_refilled: true,
/**====-----========================
|| /
|
| Event Handlers
|
|| \
/**====-----========================*/
onFieldFocus:function(e)
{
var self = this, target = e.target, config = self.config;
self.runLocalHandlers('validations', target)
.then(function(errors) {
if(!errors || errors.length == 0)
self.setFieldValid(target);
});
self.runLocalHandlers('onFocus', target, e);
},
onFieldBlur: function(e)
{
var self = this, target = e.target, config = self.config;
self.runLocalHandlers('validations', target)
.then(function(errors) {
if(!errors || errors.length == 0)
self.setFieldValid(target);
else
if(errors.length > 0)
self.setFieldInvalid(target, errors);
});
self.runLocalHandlers('onBlur', target, e);
},
onFieldKeyUp: function(e)
{
var self = this, target = e.target;
// Dont validate on TAB
if((e.which || e.keyCode) == 9)
return;
// we don't want to run validations on every single key click,
// so we delay it until they've stopped typing for a moment
self.runValidationsDebounced(target);
self.runLocalHandlers('onKeyUp', target, e);
},
onFieldKeyPress: function(e)
{
var self = this, target = e.target;
// we don't want to run validations on every single key click,
// so we delay it until they've stopped typing for a moment
self.runValidationsDebounced(target);
self.runLocalHandlers('onKeyPress', target, e);
},
/**====-----========================
|| /
|
| Private* Methods
|
|| \
/**====-----========================*/
// These fields traverse through the config
// to find the correct error/valid handler
setFieldInvalid: function(field, errors, debounced)
{
var self = this, config = self.config;
// add the errors to the cache
self.errors[field.name||field.id] = errors;
//remove the field from validFields
var index = self.validFields.indexOf(field);
if(index > -1)
self.validFields.splice(index, 1);
self.runLocalHandlers('onError', field, errors, self.errors);
// for preventing multiple config.complete() calls
self._refilled = true;
},
setFieldValid: function(field)
{
var self = this, config = self.config;
self.runLocalHandlers('onValid', field);
// remove cached errors
delete self.errors[field.name||field.id];
//add to validFields
var index = self.validFields.indexOf(field);
if(index == -1)
self.validFields.push(field);
//if entire form is valid & filled
if(self.isValid() && self._refilled)
{
config.completed(field);
self._refilled = false;
}
},
/**
* Return the local configuration for a given field or selector
* @param field
*/
getLocalHandlers: function(field)
{
var self = this;
return self.handlers[self.fields.indexOf(field)];
},
/**
* Runs local handlers for a given type and field
* @param type String
* @param field HTMLElement
* @param eventOrErrors Object If the handler is based off an event, the event should be forwarded, else if it as an onError handler, the errors should be forwarded
*/
runLocalHandlers: function(type, field, eventOrErrors)
{
var self = this;
var promise = new Promise();
var localHandlers = self.getLocalHandlers(field);
if(type == 'validations')
var errors = [];
var asyncValidationPending;
// loop through all the local handers
for(var i = 0; i < localHandlers.length; i++)
{
var handler = localHandlers[i];
if(type == 'validations')
{
var result = null;
var callback = function(asyncErrors) {
//TODO warn if Array not passed in
errors = errors.concat(asyncErrors);
promise.resolve(errors);
};
if(isFunction(handler))
result = handler(field, callback);
else
if(handler[type])
result = handler[type](field, callback);
if(typeof result === 'undefined')
asyncValidationPending = true;
else
if(result && isArray(result))
errors = errors.concat(result);
if(!asyncValidationPending && i == (localHandlers.length - 1))
promise.resolve(errors)
}
else
if(handler[type])
{
handler[type](field, eventOrErrors);
}
}
return promise;
},
/**====-----========================
|| /
|
| Public Methods
|
|| \
/**====-----========================*/
/**
* If no field is passed in, returns the Boolean validity of the entire form.
* If a field is passed in, returns the validity of that single field
*
* This does NOT go through all the fields and validate them again.
*
* Use .validate() for that.
*
* @param field
*/
isValid: function(field)
{
var self = this;
if(field)
return !self.errors.hasOwnProperty(field.id||field.name)
if(self.validFields.length !== self.fields.length)
return false;
for(var key in self.errors)
if(self.errors.hasOwnProperty(key))
return false;
return true;
},
/**
* Go through all the fields and runs validations over them.
* Or, validate a single field.
*
* @param callback {Function} Called when validations are finished
* @param runHandlers {Boolean} If true, also runs local handlers for each validation set
*/
validate: function(callback, runHandlers, field)
{
var self = this;
if(!isFunction(callback))
callback = K;
var processedFields = [];
var createRunHandlersExec = function(field) {
return function(errors) {
if(runHandlers === true)
{
if(!errors || errors.length == 0)
self.setFieldValid(field);
else if(errors.length > 0)
self.setFieldInvalid(field, errors);
}
if(processedFields.indexOf(field) == -1)
processedFields.push(field);
if(processedFields.length == self.fields.length)
callback(self.isValid());
}
};
if(field && isElement(field) && self.fields.indexOf(field) > 1)
{
self.runLocalHandlers('validations', field)
.then(createRunHandlersExec(field));
}
else
{
for(var i = 0; i < self.fields.length; i++)
{
self.runLocalHandlers('validations', self.fields[i])
.then(createRunHandlersExec(self.fields[i]));
}
}
},
/**====-----========================
|| /
|
| Init
|
|| \
/**====-----========================*/
init: function()
{
var self = this;
// fields maps to handlers index to index. The 4th index of fields is the key for the 4th value of handlers, etc etc
self.fields = []; // [input, input, input];
self.handlers = []; // [[handler], [handler, handler], [handler]];
// 1. loop through config.fields and find all fields we will be validating on
// 2. Save found fields in a flat array
// 3. Add any handlers for that field to the corresponding location in self.handlers
for(var key in self.config.fields)
{
var elements = querySelectorAllArray(key, self.form);
var handlers = self.config.fields[key];
for(var i = 0; i < elements.length; i++)
{
var field = elements[i];
//if the element has not already been found
if(self.fields.indexOf(field) == -1)
{
self.fields.push(field);
self.handlers.push([handlers]);
field.addEventListener('focus', function(e) { self.onFieldFocus.call(self, e) });
field.addEventListener('blur', function(e) { self.onFieldBlur.call(self, e) });
field.addEventListener('keypress', function(e) { self.onFieldKeyPress.call(self, e) });
field.addEventListener('keyup', function(e) { self.onFieldKeyUp.call(self, e) });
}
else
{
// the element has already been parsed, add additional handlers to it
self.handlers[self.fields.indexOf(elements[i])].push(handlers);
}
}
}
}
}
/**====-----========================
|| /
|
| Constructor
|
|| \
/**====-----========================*/
function ThatValidator(form, config)
{
var self = this;
if(isElement(form))
self.form = form;
else
if(typeof form == 'string')
self.form = document.querySelector(form);
else
logError('Please pass a valid element or selector');
if(!config)
config = defaultConfig;
// merge default config
if(typeof config === 'object')
{
for(var key in defaultConfig)
{
if(typeof config[key] === 'undefined')
config[key] = defaultConfig[key];
}
}
self.config = config;
self.errors = {}; //placeholder for any errors the form currently has
self.validFields = [ ];
self.init();
self.runValidationsDebounced = debounce(function(target)
{
var self = this;
self.runLocalHandlers('validations', target)
.then(function(errors) {
if(errors && errors.length > 0)
self.setFieldInvalid(target, errors);
else
self.setFieldValid(target);
});
}, self.config.debounceDelay);
};
// Export this shiz
if(typeof define == 'function' && define.amd)
{
// AMD support
define(function() {
return ThatValidator;
});
}
else
if(typeof module !== 'undefined' && module.exports)
{
// commonjs export
module.exports = ThatValidator;
}
else
{
// browser export
window.ThatValidator = ThatValidator;
}
/**====-----========================
|| /
|
| Space Age Utility Functions
|
|| \
/**====-----========================*/
function querySelectorAllArray(selector, element)
{
return Array.prototype.slice.call((element || document).querySelectorAll(selector));
}
function isArray(obj) {
return (Object.prototype.toString.call(obj) === '[object Array]')
}
function isElement(o){
return (
typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName==="string"
);
}
function isFunction(o) {
return (typeof o === 'function')
}
// If you use lodash and really care about every KB, replace this with `var debounce = require('lodash/function/deounce');`
function debounce(func, wait) {
var timeout, args, context, timestamp;
return function() {
context = this;
args = [].slice.call(arguments, 0);
timestamp = new Date();
var later = function() {
var last = (new Date()) - timestamp;
if (last < wait) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
func.apply(context, args);
}
};
if (!timeout) {
timeout = setTimeout(later, wait);
}
}
}
//tiny Promise impl for internal use
function Promise() {
this._thens = [];
}
Promise.prototype = {
then: function(onResolve, onReject) {
this._thens.push({ resolve: onResolve, reject: onReject });
},
resolve: function(val) {
this._complete('resolve', val);
},
reject: function(ex) {
this._complete('reject', ex);
},
_complete: function (which, arg) {
this.then = (which === 'resolve') ?
function (func) { func && func(arg); } :
function () { throw new Error("This promise has already been rejected")};
var aThen, i = 0;
while (aThen = this._thens[i++]) { aThen[which] && aThen[which](arg); }
delete this._thens;
}
};
})(window, document);