Exploring the realm of JavaScript, I find myself intrigued by the concept of creating a validation form that activates upon clicking out of the input field. Implementing various techniques to integrate this feature into an existing form has been both challenging and enlightening.
How can I seamlessly incorporate the 'blur' event into my validation form? Thank you in advance :)
function implementFormValidation(form) {
if (form === null || form.tagName.toUpperCase() !== 'FORM') {
throw new Error("The first parameter for implementing Form Validation should be a FORM element.");
}
form.noValidate = true;
form.addEventListener('submit', function(event) {
var errorExists = false;
var elementsList = this.elements;
for (var i = 0; i < elementsList.length; i += 1) {
if (! isFieldValid(elementsList[i])) {
errorExists = true;
}
}
if (errorExists) {
event.preventDefault();
}
});
// other functions remain the same as in the original code
}
HTML
<div class="content">
<form id="contact-form" method="POST" action="success.html">
<div class="form-group">
<label for="firstname">First Name</label>
<input id="firstname" type="text" name="firstname" value="" onblur="implementFormValidation('firstname');"/>
<span id="firstname-error"></span>
</div>
<!-- Other form fields omitted for brevity -->
<div class="form-group">
<button type="submit">Submit</button>
</div>
</form>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
implementFormValidation(document.querySelector('#contact-form'));
});
</script>