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?
If you add a customValidity message to the field, it becomes invalid. When you set the message as an empty string, it becomes valid again (unless it is invalid because of other reasons). field. setCustomValidity("Invalid field."); will make the field invalid.
The :invalid selector allows you to select <input> elements that do not contain valid content, as determined by its type attribute. :invalid is defined in the CSS Selectors Level 3 spec as a “validity pseudo-selector”, meaning it is used to style interactive elements based on an evaluation of user input.
The :valid and :invalid pseudo-classes are used to represent <input> elements whose content validates and fails to validate respectively according to the input's type setting.
The :invalid selector selects form elements with a value that does not validate according to the element's settings.
You 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With