-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
89 lines (64 loc) · 1.71 KB
/
script.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
const fields = document.querySelectorAll('[required]');
function ValidateField(field) {
// logica para verificar se existem erros
function verifyErrors() {
let foundError = false;
for (let error in field.validity) {
if (field.validity[error] && !field.validity.valid) {
foundError = error
}
}
return foundError;
}
function customMessage(typeError) {
const messages = {
text: {
valueMissing: "Por favor, preencha este campo"
},
email: {
valueMissing: "Email é obrigatório",
typeMismatch: "Por favor, preencha um email válido"
}
}
return messages[field.type][typeError]
}
function setCustomMessage(message) {
const spanError = field.parentNode.querySelector('span.error')
if (message) {
spanError.classList.add('active')
spanError.innerHTML = message
} else {
spanError.classList.remove('active')
spanError.innerHTML = ''
}
}
return function () {
const error = verifyErrors();
if (error) {
const message = customMessage(error);
field.style.borderColor = 'red'
setCustomMessage(message)
} else {
field.style.borderColor = 'green'
setCustomMessage()
}
}
}
function customValidation(event) {
const field = event.target;
const validation = ValidateField(field)
validation();
}
for (field of fields) {
field.addEventListener("invalid", event => {
// eliminar bubble
event.preventDefault()
customValidation(event)
})
field.addEventListener("blur", customValidation)
}
document.querySelector('form')
.addEventListener('submit', event => {
event.preventDefault();
alert('Enviado Formulario');
})