Customized error messages
by Artem
HTML
<!-- Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Data_form_validation -->
<form novalidate>
<label for="mail">I would like you to provide me an e-mail</label>
<input type="email" id="mail" name="mail" data-error="" required>
<button id="submit">Submit</button>
</form>
CSS
* {
box-sizing: border-box;
}
input {
outline: none;
}
.dirty[type="email"]:invalid {
border: 2px solid tomato;
}
.error {
position: absolute;
left: 50%;
transform: translate(-50%);
padding: 10px 15px;
background-color: #fff;
color: #333;
font-family: sans-serif;
font-size: 20px;
line-height: 30px;
}
.error.email::before {
content: "email";
}
JavaScript
var email = document.getElementById("mail");
submit.disabled = true;
const showError = (type, message, target = document.body) => {
const errorBox = document.createElement('div');
errorBox.innerText = message;
errorBox.classList.add('error');
errorBox.classList.add('type');
// should clear previous error boxes from DOM
target.append(errorBox);
setTimeout(() => {
errorBox.remove();
}, 2000);
};
email.addEventListener("keyup", function(event) {
event.target.classList.add('dirty');
console.log(email.validity, email.checkValidity(), event.target.type);
if (email.validity.typeMismatch) {
email.setCustomValidity("I expect an e-mail, darling!");
showError(event.target.type, 'I expect an e-mail, darling!');
submit.disabled = true;
} else if (email.validity.valueMissing) {
submit.disabled = true;
} else {
email.setCustomValidity("");
submit.disabled = false;
}
});