JSFiddle - React, Tailwind, and code Playground
HTML
<!doctype html>
<html>
<head>
</head>
<body>
<div class="error"></div>
<form id="target" method="post">
<label for="name">Your Name</label> <input type="text" name="name" id="name" class="required"/>
<label for="car">Your Car</label> <input type="text" name="car" id="car" class="required" />
<p><input type="submit" /></p>
</form>
</body>
</html>
CSS
.error {
display : none;
color: #D8000C;
background-color: #FFBABA;
}
JavaScript
$('#target').submit(function (e) {
var errors = {};
//No field should be blank
$('.required').each(function () {
if (!$.trim($(this).val())) errors[$(this).prev('label').text()] = 'is blank';
});
//Don't submit form on errors
//Show errors
if (!jQuery.isEmptyObject(errors)) {
$('.error').show().html("<p>Form couldn't be submitted because:</p>");
$('.error').append(
$.map(errors, function (type, error) {
return $('<p>', {
text: error + ' ' + type
}).get();
}));
// Prevent the form from being submitted
return false;
}
$('.error').hide();
});