I mean when there is an error in the input in the form due to required or empty fields, how can I style the form in that instance.
Like this
Notice how the form labels and fields are red. How can I do that?
I tried using the form submit event to find out if there are no values in the field but nothing happens. Please help.
function func() {
alert("nice!");
document.getElementById("form").submit();
var day = document.getElementById("day").value;
var month = document.getElementById("month").value;
var year = document.getElementById("year").value;
var dayLab = document.getElementById("dayLab");
var monLab = document.getElementById("monLab");
var yrLab = document.getElementById("yrLab");
if (day == null || month == null || year == null) {
dayLab.style.color = "rgb(200, 0, 0)";
monLab.style.color = "rgb(200, 0, 0)";
yrLab.style.color = "rgb(200, 0, 0)";
}
}
3
Answers
Yes, you can achieve this by adding a CSS class to the labels and inputs when an error occurs.
Apply the
required
attribute to appropriate inputs:<input type="text" required>
Add a listener on each input for the
invalid
event to add a class containing the styling you want.(optional) Add a listener on each input for the
blur
event to validate the field and either add or remove the class depending on the result.Note that if you submit a form programmatically using the
submit()
method, validation is not performed.You can make some styles when conditions are not met.