-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathform.js
72 lines (60 loc) · 1.97 KB
/
form.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
const formTextValidation = document.querySelectorAll(".form-text");
formTextValidation.forEach((item) => (item.style.display = "none"));
class ValidaForm {
constructor() {
this.form = document.forms[0];
this.form.addEventListener("submit", (e) => {
this.validar(e);
});
}
validar(e) {
e.preventDefault();
this.clearErrorMessage();
if (!this.form) return false;
//Validação campos preenchidos
let formEl = Array.from(this.form.elements);
formEl.forEach((formItem) => {
if (formItem.type !== "submit" && formItem.value == "") {
this.showError(
formItem,
`${formItem.id.replace("input", "")} não pode estar vazio...`
);
}
//Valida o CPF
if( formItem.previousElementSibling.innerText.toUpperCase().includes('CPF')){
let validaCpf = new ValidaCpf(formItem.value);
if( !validaCpf.valida() ) this.showError(formItem, 'CPF inválido...')
}
});
//Validação dos campos de senha
let passwords = document.querySelectorAll('[type="password"]');
let message = this.isInvalidPassword(passwords[0], passwords[1]);
if (message) this.showError(passwords[0], message);
}
isInvalidPassword(input1, input2) {
if (input1.value.trim() != input2.value.trim())
return "Senhas devem ser iguais...";
if (input1.value.length < 6 || input1.value.length > 8)
return "A senha deve ter entre 6 e 8 caracteres...";
return false;
}
showError(formEl, message) {
let el = document.createElement("li");
el.innerText = message;
formEl.nextElementSibling.style.display = "block";
formEl.nextElementSibling.firstElementChild.appendChild(el);
}
clearErrorMessage() {
let formElements = [...this.form.elements];
formElements.forEach((el) => {
if (el.type != "submit") {
el.nextElementSibling.firstElementChild.firstElementChild
? el.nextElementSibling.firstElementChild.removeChild(
el.nextElementSibling.firstElementChild.firstElementChild
)
: true;
}
});
}
}
let validaForm = new ValidaForm();