Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Validation styling DOM mimic
var forms = nodeListToArray(document.querySelectorAll('form'));
var customErrorClass = 'custom-error-message-style';
forms.forEach(function (formElement) {
var formFields = nodeListToArray(formElement.querySelectorAll('input, select'));
formElement.addEventListener('submit', function (e) {
var hasError = false;
removeErrorMessages(formElement);
formFields.forEach(function (field) {
if (hasError) {
return false;
}
hasError = !checkValidity(field);
});
if (hasError) {
e.preventDefault();
return false;
}
});
formElement.setAttribute('novalidate', true);
});
function nodeListToArray(nodeList) {
return Array.prototype.slice.call(nodeList);
}
function removeErrorMessages(formElement) {
var errors = nodeListToArray(formElement.querySelectorAll('.' + customErrorClass));
errors.forEach(removeErrorMessage);
return true;
}
function removeErrorMessage(error) {
var field = error.previousSibling;
if (field) {
field.removeEventListener('change', checkValidityEvent);
field.removeEventListener('keyup', checkValidityEvent);
}
error.remove();
}
function showErrorMessage(field) {
var errorMessage = [field.validationMessage];
var title = field.getAttribute('title');
var errorElement;
if (title) {
errorMessage.push(title);
}
errorElement = createErrorMessage(errorMessage, field);
field.parentNode.insertBefore(errorElement, field.nextSibling);
field.addEventListener('change', checkValidityEvent);
field.addEventListener('keyup', checkValidityEvent);
}
function checkValidityEvent(e) {
checkValidity(e.target);
}
function checkValidity(field) {
removeErrorMessages(field.parentNode);
if (field.validationMessage !== '') {
showErrorMessage(field);
return false;
}
return true;
}
function createErrorMessage(message, field) {
var element = document.createElement('div');
element.className = customErrorClass;
element.innerHTML = message.join('<br />');
return element;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment