I have an html form somthing like this:
<form id="contactForm">
<div>
<label for="name">Name</label>
<input type="text" name="name" id="name" required minlength="3" />
</div>
<button type="submit">Submit</button>
</form>
I am using html validations as my requirements are simple. And I want to display input box in red color if user has entered invalid value. I tried using css pseudo classes valid and invalid like this:
input:invalid {
background-color: red;
}
The problem with this is that all input fields show up in red even when the user has not touched the field. To prevent this issue I am using on blur event in javascript.
const contactForm = document.forms.contactForm;
const nameInp = contactForm.name;
nameInp.onblur = function () {
if (this.checkValidity()) {
console.log("valid");
} else {
console.error("invalid");
}
};
Is it possible to achieve this functionality without javascript using only pseudo classes? I do not want the input boxes to display on red until user clicks on them.