This repository has been archived by the owner on Aug 17, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathvalidation.js
84 lines (71 loc) · 1.93 KB
/
validation.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
export default class Validation {
/**
* Load up an instance of Validation
* @param {HTMLFormElement} baseForm
*/
constructor(baseForm) {
this.baseForm = baseForm;
// Load child input elements
this.inputElems = [...baseForm.querySelectorAll('input, textarea, select')];
}
/**
* Public init method
*/
init() {
let self = this;
self.bind();
}
/**
* Bind events to input elements
*/
bind() {
let self = this;
// Add an invalid listener that
self.inputElems.map(item => {
item.addEventListener('invalid', () => {
self.processValidity(item);
self.checkSiblings(item);
}, false);
});
}
/**
* Toggle the visual state of an item based on the based state key
* @param {HTMLElement} item
* @param {String} state
*/
process(item, state = 'invalid') {
switch(state) {
case 'invalid':
item.classList.add('is-error');
break;
default:
item.classList.remove('is-error');
break;
}
}
/**
* Filter sibling elements and run them through the validity checker
*
* @param {HTMLFormElement} exludedField
*/
checkSiblings(exludedField) {
let self = this;
self.inputElems
.filter(item => item !== exludedField)
.map(item => self.processValidity(item));
}
/**
* Run some checks to determine if the passed item is valid or not
* @param {HTMLElement} item
*/
processValidity(item) {
let self = this;
// If an item is valid, run the processor and bail
if(item.validity.valid) {
self.process(item, 'valid');
return;
}
// If we're here, it's invalid
self.process(item, 'invalid');
}
};