Skip to content

Instantly share code, notes, and snippets.

@magdielndantas
Created July 3, 2020 08:29
Show Gist options
  • Save magdielndantas/08b992f335997ce25877f0d07834973c to your computer and use it in GitHub Desktop.
Save magdielndantas/08b992f335997ce25877f0d07834973c to your computer and use it in GitHub Desktop.
Código para verificação de formulários com html required
const fields = document.querySelectorAll('[required]')
function validateField(field){
//verify if error true
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, preecha um email valido'
}
}
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 =>{
//bubble none
event.preventDefault()
customValidation(event)
})
field.addEventListener('blur', customValidation)
}
document.querySelector('form')
.addEventListener('submit', event =>{
console.log('send form')
event.preventDefault()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment