Is there a way to make HTML5 validate all fields at once instead of one at a time?
Using a couple of lines of JavaScript is OK but I don't really want to use an entire module for this.
I've searched quite a bit but couldn't find a clean solution for this.
Here is a sample form:
<html>
<head>
<title>Validation Test</title>
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<form action="" id="myForm" method="post">
<input id="name" name="name" required type="text">
<input id="phone" name="phone" required type="text">
<input type="submit" value="Submit">
</form>
</body>
</html>
Css file:
input:focus:required:invalid {
border: 2px solid red !important;
}
The post suggested as a possible duplicate is for having multiple validation conditions for one field, I'm looking to validate / show all invalid fields at once.
If you don't want to use jQuery, that is fine. You can easily do this with vanilla js event handlers, and DOM selectors. I'm using jQuery for the sake of saving me time.
$('#myForm').on('submit', function() {
var $inputs = $(this).find(':input'),
isValid = true;
$inputs.each(function() {
if ($(this).val() == '') {
isValid = false;
$(this).addClass('error-control');
} else {
$(this).removeClass('error-control');
}
});
return isValid
});
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