I would like to have a form that:
- Display validation messages in a custom format instead of the default style.
- Display all invalid field bubbles at once instead of one at a time.
Right now, I am stuck with the boring browser-specific message appearance and I don’t see the next error until I correct the last one. This is a really bad user experience, so looking for a few pointers on how to address this.
This is my current JavaScript code:
const contactUsForm = document.querySelector('#Form');
if (contactUsForm) {
function Validate() {
validatedFields = contactUsForm.querySelectorAll('[data-validation-required],[data-validation-format]');
validatedFields.forEach(field => {
/* RegEx patterns */
const emailPattern = /^((([a-z]|d|[!#$%&'*+-/=?^_`{|}~]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])+(.([a-z]|d|[!#$%&'*+-/=?^_`{|}~]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])+)*)|((x22)((((x20|x09)*(x0dx0a))?(x20|x09)+)?(([x01-x08x0bx0cx0e-x1fx7f]|x21|[x23-x5b]|[x5d-x7e]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(\([x01-x09x0bx0cx0d-x7f]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))))*(((x20|x09)*(x0dx0a))?(x20|x09)+)?(x22)))@((([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])*([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))).)+(([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])*([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])))$/i;
if (field.getAttribute('type') === 'email')
{
field.setAttribute('pattern', emailPattern);
}
if (field.validity.valueMissing) {
field.setCustomValidity(field.dataset.validationRequired);
}
else if (field.validity.patternMismatch) {
field.setCustomValidity(field.dataset.validationFormat);
}
else {
field.setCustomValidity('');
}
field.reportValidity();
contactUsForm.checkValidity();
/* Recheck on field value change */
field.addEventListener('change', function() {
field.setCustomValidity('');
Validate();
});
});
}
Validate();
contactUsForm.addEventListener('submit', function(e) {
e.preventDefault;
if (e.checkValidity() == false) {
return false;
}
else {
// form.submit()
}
});
}