I have created a form and decided to validate it with just HTML5 and some JS without any additional plugins. So all of my required inputs have required
attribute.
Here is the CSS to make them look nice
input:invalid {
border: 2px solid #c15f5f
}
It sets the border of the invalid
inputs to red, even if they haven't been touched yet.
How to make input:invalid
apply after clicking submit button, along with the error messages?
I have created a form and decided to validate it with just HTML5 and some JS without any additional plugins. So all of my required inputs have required
attribute.
Here is the CSS to make them look nice
input:invalid {
border: 2px solid #c15f5f
}
It sets the border of the invalid
inputs to red, even if they haven't been touched yet.
How to make input:invalid
apply after clicking submit button, along with the error messages?
3 Answers
Reset to default 15You can add a class to the form when the submit-button was clicked and adjust your CSS selector so it only matches the input fields in a submitted form:
document.getElementById("submitButton").addEventListener("click", function(){
document.getElementById("testForm").className="submitted";
});
form.submitted input:invalid{
border:1px solid red;
}
<form id="testForm">
<input type="text" required>
<input type="submit" value="submit" id="submitButton">
</form>
Building on Thomas' solution and idlefinger's comment, I would suggest listening for the HTML5 invalid event, which fires prior to the submit event.
// save all form controls as variable
var inputs = document.getElementById("your-form").elements;
// Iterate over the form controls
for (i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("invalid", function(){
document.getElementById("your-form").className="submitted";
});
};
form input {
background: #eee;
}
form.submitted input:invalid {
background: #ff3b3b;
}
<form id="your-form">
<input type="text" required>
<input type="text">
<input type="submit" value="submit">
</form>
this works for me:
input:invalid:not([value='']) {
outline: none;
border: 2px solid #c15f5f;
}
but I prefer using box-shadow rather than border or outline (the default)