-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathform-validation.js
98 lines (89 loc) · 3.36 KB
/
form-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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
class FROMVALIDATION {
constructor() {
this.forms = document.querySelectorAll("[data-form]");
this.name = null;
this.email = null;
this.number = null;
this.message = null;
this.button = null;
this.init();
}
init() {
this.eventListener();
}
eventListener() {
this.forms.forEach(form => {
this.nameValidator(form.elements["name"]);
this.emailValidator(form.elements["Email"]);
this.numberValidator(form.elements["Number"]);
this.messageValidator(form.elements["field"]);
form.addEventListener('submit', (evt) => {
evt.preventDefault()
this.button = evt.target.querySelector(".submit-button");
if ((this.name && this.email && this.number && this.message) != null) {
if (!this.button.classList.contains("success")) {
this.button.classList.add("success");
this.button.value = "Message sent";
}
if (this.button.classList.contains("failed")) {
this.button.classList.remove("failed");
}
}
else {
this.button.classList.add("failed");
this.button.value = "Something went wrong!";
}
})
})
}
nameValidator(name) {
name.addEventListener("blur", (evt) => {
if (name.value != "" && name.value != null && name.value.length > 3 && !name.value.match(/\d+/g)) {
this.name = name.value;
evt.target.classList.remove("invalid")
evt.target.classList.add("valid");
}
else {
evt.target.classList.remove("valid");
evt.target.classList.add("invalid");
}
})
}
emailValidator(email) {
email.addEventListener("blur", (evt) => {
if (email.value != "" && email.value != null && email.value.length > 3 && email.value.match(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)$/)) {
this.email = email.value;
evt.target.classList.add("valid");
}
else {
evt.target.classList.remove("valid");
evt.target.classList.add("invalid");
}
})
}
numberValidator(number) {
number.addEventListener("blur", (evt) => {
if (number.value != "" && number.value != null && number.value.length > 3 && number.value.match(/^\+91 +[0-9]{10}$/)) {
this.number = number.value;
evt.target.classList.add("valid");
}
else {
evt.target.classList.remove("valid");
evt.target.classList.add("invalid");
}
})
}
messageValidator(message) {
message.addEventListener("blur", (evt) => {
if (message.value != "" && message.value != null && message.value.length > 10) {
this.message = message.value;
evt.target.classList.add("valid");
}
else {
evt.target.classList.remove("valid");
evt.target.classList.add("invalid");
}
})
}
}
new FROMVALIDATION;