I\'m building a form and I want to use the :invalid
selector to give the \"required\" input fields a red border if the user presses submit without filling them, but
Old question, but for people that might might find it useful: I made a little script that adds a class to a form when it's attempted to be submitted, so that you can style forms that have and haven't been attempted to be submitted differently:
window.addEventListener('load', function() {
/**
* Adds a class `_submit-attempted` to a form when it's attempted to be
* submitted.
*
* This allows us to style invalid form fields differently for forms that
* have and haven't been attemted to submit.
*/
function addFormSubmitAttemptedTriggers() {
var formEls = document.querySelectorAll('form');
for (var i = 0; i < formEls.length; i++) {
function addSubmitAttemptedTrigger(formEl) {
var submitButtonEl = formEl.querySelector('input[type=submit]');
if (submitButtonEl) {
submitButtonEl.addEventListener('click', function() {
formEl.classList.add('_submit-attempted');
});
}
}
addSubmitAttemptedTrigger(formEls[i]);
}
}
addFormSubmitAttemptedTriggers();
});
Now forms that are attempted to be submitted will get a class _submit-attempted
, so you can only give these fields a red box shadow:
input {
box-shadow: none;
}
form._submit-attempted input {
box-shadow: 0 0 5px #F00;
}