-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
257 lines (207 loc) · 6.26 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
(function() {
const greatMessage = "LightValidator has been instancied";
const errorStyle =
"color: #ffffff; background: #fd4042; padding: 5px; font-size: 15px;";
const ERR_MSG_FORM_ID_MISSED = '"id: YOUR_FORM_ID" option must be defined';
// Ligth Form Validator constructor
this.LightValidator = function(element, options) {
const defaultOptions = {
className: "light-validator"
// Future options goes here
};
this.element = element;
// Plugin options
// Create options by extending defaultOptions with the passed in arugments, assing defaultOptions otherwise
this.options = extendDefaultOptions(defaultOptions, options);
if (verifyOptions.call(this)) {
this.form = getForm(element);
}
helloMsg();
};
LightValidator.prototype.validate = function() {
return new Promise(resolve => {
const _ = this;
const form = _.form;
onKeyUp(form);
form.addEventListener("submit", function(e) {
e.preventDefault();
const formDatas = serializeForm(form);
if (formHasError(form)) {
throwError(`Form has error`);
}
resolve(formDatas);
return formDatas;
});
});
};
/**
* Resets form elements
*
* @param {Node} form The form node
*/
LightValidator.prototype.reset = form => {
loopElements(form, element => {
switch (element.tagName.toLowerCase()) {
case "select":
element.querySelector("option").selected = "selected";
break;
default:
element.value = "";
}
});
};
/**
*
*
* @param {Node} form
* @return {Boolean}
*/
const formHasError = form => {
var errorList = [];
loopElements(form, element => {
errorList.push(processFielValidation(element, false));
});
return errorList.indexOf(true) !== -1;
};
/**
* Loops all form elements and process item in the given callback function
*
* @param {Node} form
* @param {Function} callback A callback function
*/
const loopElements = (form, callback) => {
getElements(form).forEach(element => {
callback(element);
});
};
const getFormChildren = (form, type, selector) => {
return form[`querySelector${type}`](selector);
};
const getElements = form => {
return getFormChildren(form, "All", "[name]");
};
const processFielValidation = (element, checkError) => {
const $parent = element.closest("div");
if (element.required) {
if (element.value === "") {
element.classList.add("invalid-field");
$parent.classList.add("invalid-field-wrapper");
showInvalidMessage($parent, element.name);
if (checkError !== undefined) {
checkError = true;
}
} else {
$parent.classList.remove("invalid-field-wrapper");
element.classList.remove("invalid-field");
if (element.type === "email") {
const emailValue = element.value;
if (!validEmail(emailValue)) {
showInvalidMessage(
$parent,
"",
`<strong><em>${emailValue}</em></strong> is not an email address valid`
);
} else {
removeInvalidMessage($parent);
}
} else {
removeInvalidMessage($parent);
}
}
}
return checkError;
};
/**
* Trigger form validation on form element KeyUp
*
* @param {Node} form The form node
*/
function onKeyUp(form) {
loopElements(form, function(element) {
element.onkeyup = function() {
processFielValidation(this);
};
});
}
/**
* Serializes form
*
* @param {Node} form The form node
* @return {Object} The form datas { name: value }
*/
const serializeForm = form => {
const serialized = {};
loopElements(form, element => {
const elementType = element.type;
if (
(elementType === "radio" && element.checked) ||
elementType !== "radio"
) {
serialized[element.name] = element.value;
}
});
return serialized;
};
function removeInvalidMessage(parent) {
const $invalidMessage = getFormChildren(parent, "", ".invalid-message");
if ($invalidMessage) {
$invalidMessage.parentNode.removeChild($invalidMessage);
}
}
function showInvalidMessage(parent, fieldName, custom) {
const div = document.createElement("div");
const userMessageError = parent.querySelector("[data-error]");
removeInvalidMessage(parent);
div.classList.add("invalid-message");
if (userMessageError) {
div.textContent = userMessageError.dataset.error;
} else {
div.innerHTML = custom
? custom
: `<strong><em>${fieldName}</em></strong> is required.`;
}
parent.appendChild(div);
}
const validEmail = value => /^.+@.+\..{2,}$/.test(value);
function verifyOptions() {
const formId = this.element;
if (!formId) {
throwError(ERR_MSG_FORM_ID_MISSED);
}
return true;
}
const getForm = formId => {
const formNode = document.getElementById(formId);
if (!formNode) {
throwError(`Form with id "${formId}" not found`);
}
const nodeName = formNode.nodeName.toLowerCase();
if (nodeName !== "form") {
throwError(
`LightValidator element must be a <form>, <${nodeName}> given`
);
}
return formNode;
};
const throwError = message => {
console.info(`%c ❌ ${message} `, errorStyle);
throw message;
};
// Extends defaultOptions with the provided options
const extendDefaultOptions = (defaultOptions, options) => {
let property;
for (property in options) {
if (options.hasOwnProperty(property)) {
defaultOptions[property] = options[property];
}
}
return defaultOptions;
};
const helloMsg = () => {
// console.log(`%c Hello`, 'font-weight: bold, font-size: 18px, color: #1d1e3d')
console.log(
`%c 🥳 ${greatMessage} `,
"color: #1d1e3d; background: #bcbcbc; padding: 5px; font-size: 15px;"
);
};
})();