Enhancing a validation form with the 'onblur' event handler

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>

Explore the working example here!

Answer №1

It is always better to avoid using element attributes like "onblur" for executing JavaScript events. Instead, you can add event listeners in your JavaScript code.

In order to improve your code, I have made the following changes:

  1. Removed all "onblur" attributes
  2. Added JavaScript code to listen for blur events on the entire form (all elements).

Here is the updated JavaScript snippet:

theForm.addEventListener('blur', function(evt) {
    console.log(evt);
}, true);

You can view the updated code on JS Fiddle here: http://jsfiddle.net/82n9ab4s/1/

Reminder: addEventListener method requires 3 parameters - 1. Event type 2. Function to execute 3. Boolean value indicating whether the event should bubble up or not.

Essentially, in this code, the event occurs on the input element within the form and then bubbles up to the form itself. You can confirm this by examining the event variable (evt).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What's the best way to iterate through multiple objects within <td> tags using Vue.js?

I have an Array filled with multiple Objects, and now I am interested in iterating through each object as a <tr> within a <table>. I have successfully achieved this. However, some of these objects might contain nested objects. In such cases, I ...

What are some ways to maintain code efficiency when working with AJAX requests?

Looking at the code below, I am making two identical Ajax requests with only one line of difference. Is there a way to consolidate this into a function to maintain DRY (Don't Repeat Yourself) code? $('.searchable').multiSelect({ selecta ...

Obtain a collection of strings from an array of objects based on specified criteria

What is the most efficient method to extract an array of specific strings from an array of objects, where a certain condition needs to be met? Solution Attempt: const array = [{ "Item": "A", "Quantity": 2 ...

Looking to update the location of an element within a canvas using Vue and socket.io?

I am currently developing a 2D pong game using vue.js and socket.io. At the moment, I have a black rectangle displayed in a canvas. My goal is to make this rectangle move following the cursor of my mouse. The issue I am facing is that although my console l ...

Learning React: Error - Unable to access the 'data' property when it is null

Currently, I am learning React by following a tutorial available at this link: http://facebook.github.io/react/docs/tutorial.html Specifically, I am focusing on the section related to fetching data from the server, which can be found here: http://facebook ...

Is it recommended to create model classes in React components?

Within the realms of React, the Flux architecture is utilized. According to https://reactjs.org/docs/thinking-in-react.html, React operates with two distinct models - namely, the state and props. There are recommendations provided for model management in ...

What is the method or variable called "afterShow" used for in FancyBox V4 and how does it differ from its counterpart in JQuery-FancyBox V3?

We previously utilized the V3 edition of Fancybox, incorporating our increaseImageClicks and increaseVideoClicks functions within its afterShow function: /* FANCYBOX OLD (https://web.archive.org/web/20210325170940/https://fancyapps.com/fancybox/3/docs/): * ...

The functionality of the Vueify modal seems to be malfunctioning when incorporating Vueify alongside a central Modal.vue file that houses modal templates

I've been experimenting with integrating this tutorial on creating reusable modal dialogs with Vuejs and adapting it for use with Vueify. Initially, I was able to successfully implement it, but after exploring a different approach briefly, I returned ...

When the input field is clicked, the file:/// URL is sent

Currently, my HTML page contains a form that includes an input field for URLs. Ideally, upon typing in the URL and clicking the button, I intend to be redirected to that website. However, the issue lies in the fact that instead of redirecting me to the p ...

Having trouble getting a local npm installation to work from a specific file path?

After following the instructions from this helpful link to install an npm package through a file path, I encountered an error when attempting to use it: Cannot find module '<module_name>' or its corresponding type declaration Are there an ...

What is the process for utilizing AngularJS's multiple $http calls to retrieve data from a single PHP file?

I'm currently experimenting with multiple AngularJS ajax calls to a single php file in order to retrieve different json data based on the request. Below is the code snippet I am working with: var myApp = angular.module('myApp', []); myApp ...

I am unable to access the state after setting it in useEffect in React. Why is this happening?

After rendering the component, I utilize socket io to send a socket emit in order to fetch data within the useEffect hook. Subsequently, I also listen for the data that is returned. However, upon receiving the data back from the socket, I update the stat ...

Guide on how to retrieve server error responses in javascript using axios

I am currently using axios to send form data to a Laravel backend. While I can easily access the response upon success, I am facing difficulties retrieving the error response. In my browser's developer tools, under network > response, I see the follo ...

Is it possible to attach a mouse click event to styled text?

Is there a way to specify a mouse click event for an element with a decoration applied to the text, matched with regex? The option to specify a hoverMessage is available, but I would like to find a way to execute a function based on which decorated text ...

Unable to create account using PHP

Every time I attempt to create an account, the data I receive is always problematic. The username must be between 3 and 15 characters I find it frustrating that the account creation never goes through successfully. What baffles me even more is that af ...

Is it possible to move a directive within a limited parent element?

Is there a way to limit the movement of an angular.js drag directive within the confines of its parent element? You can see the problem I'm facing in this jsbin: http://jsbin.com/maxife/3/edit?html,css,js,output ...

What is the best way to break out of a function halfway through?

What are your thoughts on using nested if statements? $scope.addToCart = function () { if (flagA) { if (flagB) { if (flagC) { alert('nononono!'); return; } } } e ...

Encountering a 400 bad request error when attempting to utilize AJAX within a WordPress environment

I am encountering a 400 error while attempting to retrieve the response from WordPress AJAX. Despite multiple attempts, I have been unable to pinpoint the root cause of the issue. The jQuery version being used is 3.6 and the filter.js file appears to be fu ...

How to eliminate the comma from the final element in a JavaScript Vue.js array?

I'm looking to remove the comma from the last element in Vue, but I'm unsure how to do so since the index of the last element is unknown. <td v-if="category.sub_category.length > 0"> <template v-for=&q ...

What is the best method for efficiently loading SVG icons on an HTML page without redundancy? / Is utilizing <use href> recommended?

My struggle with implementing icons in Angular While working on a new Angular project, I've encountered challenges with my current SVG-icon implementation method from a previous project (@ngneat/svg-icon). The process involves organizing SVG files in ...