Skip to content

Instantly share code, notes, and snippets.

@byverdu
Created February 14, 2015 12:18
Show Gist options
  • Save byverdu/398f0f9a02fa502ccc23 to your computer and use it in GitHub Desktop.
Save byverdu/398f0f9a02fa502ccc23 to your computer and use it in GitHub Desktop.
function changeFormUI(form) {
// deshabilitar el actual comportamiento
form.addEventListener('invalid', function(event) {
event.preventDefault();
}, true);
// Support Safari and Android browser
form.addEventListener('submit', function(event) {
if (!this.checkValidity()) {
event.preventDefault();
}
});
var button = form.querySelector('button');
// Añadir nuevo comportamineto
button.addEventListener('click', function() {
var label,
error,
invalid = form.querySelectorAll(':invalid'),
allErrors = document.querySelectorAll('.error');
// eliminar antiguao errores
for (i = 0; i < allErrors.length; i++) {
allErrors[i].remove();
}
for (i = 0; i < invalid.length; i++) {
// Aplicar estilo solo a los elementos que validan
if (invalid[i].willValidate) {
error = document.createElement('div');
error.className = 'error';
error.textContent = invalid[i].validationMessage;
label = invalid[i].parentNode;
label.insertBefore(error, invalid[i].nextSibling);
}
}
// Evento focus al primer elem con error
if (invalid.length > 1) {
var arr = [];
[].map.call(invalid, function(val) {
if (val.willValidate) {
arr.push(val);
}
});
arr[0].focus();
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment