-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
96 lines (77 loc) · 2.19 KB
/
Copy pathscript.js
File metadata and controls
96 lines (77 loc) · 2.19 KB
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
const form = document.querySelector("form");
const inputs = form.querySelectorAll("input");
inputs.forEach((input) => {
input.addEventListener("change", () => {
validateInput(input);
});
});
// disable browsers validation
form.noValidate = true;
// handle form submit event
form.addEventListener("submit", (e) => {
if (!form.checkValidity()) {
e.preventDefault(); // prevent form submission
inputs.forEach(validateInput);
} else {
alert("form submitted successfully!");
// Send data to the backend
}
});
const validateInput = (input) => {
let errorText = input.nextElementSibling;
if (!errorText) {
errorText = document.createElement("small");
errorText.className = "error-text";
input.insertAdjacentElement("afterend", errorText);
}
input.setCustomValidity("");
if (input.validity.patternMismatch) {
input.setCustomValidity(input.title);
}
checkValidationRules(input);
input.classList.toggle("invalid", !input.checkValidity());
errorText.textContent = input.validationMessage;
};
const rules = {
username: {
disallowedWords: {
words: ["offensive", "inappropriate"],
error: "Username is invalid. Please choose another one.",
},
},
"password-conf": {
match: {
target: "password",
error: "Passwords do not match",
},
},
};
const checkValidationRules = (input) => {
// skip inputs with no custom validation
if (!rules[input.id]) return;
for (const rule in rules[input.id]) {
applyValidationRule(rule, input);
}
};
const applyValidationRule = (rule, input) => {
const ruleset = rules[input.id][rule];
let error = ruleset.error;
switch (rule) {
case "match":
const matchInput = document.getElementById(ruleset.target);
if (!matchInput) {
throw new Error(`${ruleset.target} field is not found`);
}
if (input.value !== matchInput.value) {
input.setCustomValidity(error);
}
break;
case "disallowedWords":
// join the banned words into string and make it case insensitive
const words = new RegExp(ruleset.words.join("|"), "i");
if (words.test(input.value)) {
input.setCustomValidity(error);
}
break;
}
};