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

Guide to transforming an embed/nested FormGroup into FormData

Presenting my Form Group: this.storeGroup = this.fb.group({ _user: [''], name: ['', Validators.compose([Validators.required, Validators.maxLength(60)])], url_name: [''], desc: ['', Validators.compose([Valida ...

What is the best way to display a div box only when a user checks a checkbox for the first time out of a group of checkboxes, which could be 7 or more, and then hide the

Is there a way to make a div box appear when the user checks any of the first checkboxes? I have attempted using the following codes: JQ Codes: $('#checkbox').change(function() { if ($(this:first).is(':checked')) { cons ...

Export nested objects from an AngularJS JSON array to a CSV file

When I download my data into a CSV file, the display setting is showing as "[object Object]". This is not the desired outcome. https://i.stack.imgur.com/ej2UO.png The expected display should look like this: https://i.stack.imgur.com/8JJ88.png This is p ...

Can you eliminate the commas and turn it into a string?

function EncryptMessage(message) { var encryptedArr = []; for(i=0;i<message.length+1;i++){ var unicode = message.charCodeAt(i); var encryptedUnicode; var newCharacter = String.fromCharCode(encryptedUnicode); if( ...

Is there a way to extract the query string from a file in order to query the database using ExpressJS?

I am having trouble with this code snippet as it doesn't seem to be working properly. var content = fs.readFileSync('/home/diegonode/Desktop/ExpressCart-master/views/partials2/menu8xz.hbs', 'utf8' ); req.db.products.find( co ...

Monitor files in different directories with the help of pm2

Can pm2 detect changes in directories outside of the current one? For example, if I have an index.js file in /home/sprguillen/workspace/node that needs to be run by pm2, but my configuration file is located outside in /home/sprguillen/workspace/config. I ...

Ancient queries carry the weight of time

Extremely ancient, very old, incredibly aged beyond belief ...

What is the best way to utilize the sx prop in Material UI for applying styles specifically when the component is active or selected?

In the code snippet below, I have set up the useState hook so that when a ListItem is clicked on, the selected state becomes true. My goal is to apply specific styling when an item is selected using the sx prop instead of creating a styled component for su ...

JavaScript: Adjust DIV Width Based on Window Height

Is there a way to make the width of a div equal to the height of the window in jquery? I attempted this method: <script type="text/javascript"> $(".rt-container").style.width = $(window).height(); </script> Unfortunately, it did not work. I ...

Issues arise when attempting to enforce type-safety in TypeScript while using the JSON.parse

Is it possible that type-safety is compromised in TypeScript when dealing with JSON parsing? I should be triggering an error, but I'm not: interface Person { name: string } const person: Person = somePossibleFalsey ? JSON.parse(db.person) : undefi ...

Display of Navigation Bar in Angular is Not Proper

Currently diving into the world of Angular, I've encountered an issue with a material menu that isn't displaying correctly. The expected outcome based on my code should resemble this image: https://i.stack.imgur.com/z70Aq.png This snippet showc ...

Techniques for implementing a PHP base_url() function in a JavaScript file

I need to pass base_url from the Book Controller to the book.js file This is the function within book.js function loadPage(page, pageElement) { // Create an image element var img = $('<img />'); img.mousedown(function(e) { ...

Remove data from Firebase that is older than two hours

I need to implement a solution to automatically delete data that is older than two hours. Currently, I am iterating through all the data on the client-side and deleting outdated entries. However, this approach triggers the db.on('value') function ...

Releasing Typescript 2.3 Modules on NPM for Integration with Angular 4

Although there are instructions available in Writing NPM modules in Typescript, they are outdated and there are numerous conflicting answers that may not be suitable for Angular. Additionally, Jason Aden has delivered an informative presentation on youtu ...

Some models showcase crisp textures with Thee.js, while others appear hazy (especially custom designs)

As a beginner in the realm of Three.js, I have been following a tutorial on texturing custom geometric shapes. The tutorial used a classic head OBJ file as a test case, which worked perfectly fine. However, when I tried to tweak the script to render my own ...

Verify if the connection to MongoDB Atlas has been established for MongoDB

When working with MongoDB, I find myself switching between a local database during development and MongoDB Atlas in production. My goal is to implement an efficient text search method that utilizes $search when connected to MongoDB Atlas, and $text when co ...

How to prevent v-menu from overlapping a navbar in Vue.js

Exploring the examples on the main page of Vuetify, we come across the v-menu component showcased in detail. Check it out here: https://vuetifyjs.com/en/components/menus/#accessibility If you activate any of the buttons to open the v-menu and then scroll ...

Tips for showcasing timestamps within a Vue.js/Firebase application

In my current project, I am working on developing a chat application using Vue.js and Firebase. The codebase I am referring to can be found at https://github.com/jsfanatik/vuestacks-chat-vue-firebase. I have successfully implemented the Chat component to a ...

Gulp and Vinyl-fs not functioning properly when trying to save in the same folder as the source file due to issues with

After exploring a variety of solutions, I have yet to find success in modifying a file in place using Gulp.js with a globbing pattern. The specific issue I am facing can be found here. This is the code snippet I am currently working with: var fstrm = re ...

Using JavaScript to save a file with a data URL in Internet Explorer

Need help with file conversion on different browsers. I developed an app that converts files, and everything was working perfectly in Chrome. However, when it comes to IE (10/11/Edge), I'm facing some challenges: 1) The HTML5 download attribute does ...