-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformValidation.js
48 lines (45 loc) · 1.35 KB
/
formValidation.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
/*
formValidation.js
25/January/2022
*/
const formCtrl = document.getElementById('form');
const nameCtrl = document.getElementById('name');
const emailCtrl = document.getElementById('email');
const errorCtrl = document.getElementById('error');
const commentsCtrl = document.getElementById('comment');
emailCtrl.addEventListener('input', () => {
if (emailCtrl.validity.valid) {
errorCtrl.textContent = ''; // Reset the content of the message
}
});
formCtrl.addEventListener('submit', (e) => {
if (!nameCtrl.checkValidity()) {
nameCtrl.reportValidity();
e.preventDefault();
return;
}
if (!commentsCtrl.checkValidity()) {
commentsCtrl.reportValidity();
e.preventDefault();
return;
}
const email = emailCtrl.value;
const regex = /([A-Z])/g;
if (email.search(regex) !== -1) {
emailCtrl.setCustomValidity('Not good');
emailCtrl.reportValidity();
errorCtrl.textContent = 'Expecting lowercase letters';
emailCtrl.setCustomValidity('');
e.preventDefault();
return;
}
// Check if is a valid email address
const regEmail = /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9-]+)*$/g;
if (email.search(regEmail) === -1) {
errorCtrl.textContent = 'Expecting a valid email address';
e.preventDefault();
return;
}
// If the form is submited then clear the local storage
localStorage.clear();
});