Real-time form validation in Bootstrap 4 while completing the form

After exploring the form validation section in Bootstrap 4.4 (https://getbootstrap.com/docs/4.4/components/forms/#how-it-works), I have successfully integrated the code into my project. The code example and script for triggering validation seem quite impressive!

I've been pondering whether it's feasible to enable this validation while the user is still filling out the form, rather than waiting until they attempt to submit it?

For example, if there are two required input fields - First Name & Last Name, can I validate each field as soon as it's filled out (e.g., changing focus from one field to another)?

In other words, real-time validation?

The current validation method I'm using (activated when clicking the form submit button) is:

function validateForm () {
  var forms = document.getElementsByClassName('needs-validation')
  var validation = Array.prototype.filter.call(forms, function(form) {
    console.log(form.checkValidity())
    if (form.checkValidity() === false) {
      event.preventDefault()
      event.stopPropagation()

      // get the "first" invalid field
      var errorElements = document.querySelectorAll('.form-control:invalid')

      // scroll the user to the invalid field
      window.scrollTo(0, getOffset(errorElements[0]).top)

    }
    form.classList.add('was-validated')
  })
}

Answer №1

The checkValidity() function can be applied to individual inputs for validation. By binding the blur event handler to each input, you can add classes is-valid or is-invalid based on the validation results.

(function() {
  'use strict';
  window.addEventListener('load', function() {
    // Select all the forms where custom validation styles will be used
    var inputs = document.getElementsByClassName('form-control')

    // Iterate over each input and monitor the blur event
    var validation = Array.prototype.filter.call(inputs, function(input) {

      input.addEventListener('blur', function(event) {
        // Reset classes
        input.classList.remove('is-invalid')
        input.classList.remove('is-valid')

        if (input.checkValidity() === false) {
            input.classList.add('is-invalid')
        }
        else {
            input.classList.add('is-valid')
        }
      }, false);
    });
  }, false);
})()

Answer №2

To ensure validation upon leaving an input field, you can implement a blur event listener that triggers your function.

const formInputs = document.querySelectorAll("#form input");

formInputs.forEach(input => input.addEventListener("blur", validateInput));
<form id="form">
  <input type="text" placeholder="Enter text here">
  <input type="text" placeholder="Enter more text">
</form>

Answer №3

@Samantha P In response to @Dan K's query, I integrated the default Bootstrap code with real-time validation into the @Zim code to prevent form submission if there are any invalid fields. The modified code is shown below:

// Enhancing JavaScript functionality to block form submissions with invalid fields
(function() {
    'use strict';
    window.addEventListener('load', function() {
        // Gathering all forms requiring custom Bootstrap validation styles
        var forms = document.getElementsByClassName('needs-validation');
        
        // Looping through forms and halting submission
        var formValidation = Array.prototype.filter.call(forms, function(form) {
            form.addEventListener('submit', function(event) {
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                } else {
                    event.preventDefault(); 
                    processForm();
                }
                form.classList.add('was-validated');
            }, false);
        });
        
        // Additional code for checking each input field
        var inputs = document.getElementsByClassName('form-control');
        var inputValidation = Array.prototype.filter.call(inputs, function(input) {
            input.addEventListener('blur', function(event) {
                input.classList.remove('is-invalid');
                input.classList.remove('is-valid');
                if (input.checkValidity() === false) {
                    input.classList.add('is-invalid');
                } else {
                    input.classList.add('is-valid');
                }
            }, false);
        });
        
    }, false); // End of window load event listener
})(); // End of immediately invoked function container

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

Flexible design for both columns and rows

Currently utilizing Bootstrap 4, I am attempting to achieve the layout depicted in the image below: https://i.sstatic.net/P1g0t.png My current outcome looks like this: https://i.sstatic.net/AHPDl.png This issue arises on screens with a width exceeding ...

What is the reason behind event bubbling failing to function properly when CSS grid is utilized and elements are placed in the same cell

I am facing an issue with two grid children occupying the same cell and both having click event listeners. As per the concept of event bubbling, I expect both event listeners to be triggered when I click on the cell. const outer = document.getElementByI ...

The PHP file fails to load JavaScript because it requires another JavaScript file to be loaded beforehand

I created a chat widget using PHP (chat.php) and now I want to embed it into another PHP page (blank.php). To make this work, chat.php requires some scripts that are located in external JavaScript files. So, in blank.php, I added the necessary JS files th ...

What is the best way to access a component's value from a different component in Vue script?

I have two Vue components in my PHP file: "application" and "vn" component. I am trying to fetch {{obj.vacancies_left}} from the "vn" component and use it in the "application" component. However, I keep getting an undefined variable error. I attempted to r ...

Guide on Verifying File Existence through URL using JavaScript

Can someone assist me with this code? http://jsfiddle.net/geetyn6f/422/ I am looking to input the URL in the designated field. Upon clicking 'Check', I want the result to display in the second input instead of an alert. URL: <input type="t ...

Ensuring validation on an input field following the addition of a new field sharing the same class

Whenever the "Add" button is clicked, an input field with the same class name should be created. However, a validation check needs to be performed before creating the input field. The issue is that the validation is only working the first time and not duri ...

The website is displaying a strange mix of text and HTML when viewed on a PC

While browsing the internet for C programs, I stumbled upon this particular program that caught my eye: <span style='color:#004a43'>#</span><span style='color:#004a43'>include</span><span style='color:#8 ...

What could be the reason why the AngularJS form is set to read-only

Explaining the setup of my app in HTML: <div ng-app="md-app"> <div id="general"> <ng-include src="template1" ng-controller="GeneralCtrl"></ng-include> </div> </div> The JavaScript function to fetch a pe ...

Error 404 encountered while attempting to access dist/js/login in Node.JS bootstrap

I currently have a web application running on my local machine. Within an HTML file, I am referencing a script src as /node_modules/bootstrap/dist/js/bootstrap.js. I have configured a route in my Routes.js file to handle this request and serve the appropri ...

Enhancing the aesthetic appeal of a form

I have created a form in HTML that utilizes JavaScript to pull data from a database. I am looking to style the form, but I'm unsure of how to proceed. Below is the form along with some CSS code. How can I integrate the two together? <form id=" ...

To make changes to an item, simply tap on the Catalog number

I'm currently facing a challenge in trying to implement a modal window that displays detailed information about a selected item based on the catalog number. The catalog number serves as the trigger to open the modal. Since I'm relatively new to a ...

a dedicated TypeScript interface for a particular JSON schema

I am pondering, how can I generate a TypeScript interface for JSON data like this: "Cities": { "NY": ["New York", [8000, 134]], "LA": ["Los Angeles", [4000, 97]], } I'm uncertain about how to handle these nested arrays and u ...

Utilize JavaScript in conjunction with encfs for enhanced encryption capabilities

I am attempting to access an encfs filesystem using JavaScript, but am struggling to understand the correct approach. I am utilizing the CryptoJS library for this task. The .ecnfs6.xml file contains standard settings and uses the password "123456": < ...

Detecting changes in URL hash using JavaScript - the ultimate guide

What is the most effective method for determining if a URL has changed in JavaScript? Some websites, such as GitHub, utilize AJAX to add page information after a # symbol in order to generate a distinct URL without having to refresh the page. How can one ...

Saving an item using localStorage

I've been struggling to figure out how to make localStorage save the clicks variable even after refreshing the browser. Initially, I attempted using JSON.stringify and JSON.parse but later discovered that using parseInt could be a more suitable optio ...

Developing distinct state values for assigned objects

I developed a star rating component using Material UI components that is based on a mapped object. However, I am facing an issue where all the star ratings show the same value when clicked. How can I ensure that each star section displays its own value bas ...

Firefox triggers VideoJS event 'ended' at the beginning

When I use video JS, the "ended" event in Firefox is triggered both at the end and beginning of the video playback. Check out this example in FF: http://jsfiddle.net/planadecu/a3Chu/ All other browsers seem to work fine with this. The code snippet calle ...

What is the method for determining the variance between two values?

What is the best way to calculate the difference between two values? For example, if we have 0.0.0.1.0 and 0.0.0.1.12, the difference between them is 12. I attempted using Math.abs() but this only works for single digits. ...

The setState function has not been called

I am facing an issue where my setState method is not getting invoked. Even after setting the state, the value remains at the default value when printed. This problem occurs while using Expo. Here is my code snippet: import React from 'react'; ...

Creating interactive routes and pages using Next.js and Prisma, embracing dynamic functionality

I have product information cards stored in my database, and I successfully display them on the user's page. Now, I want to add a "More Details" button on each card that will link to a new page (/pages/card/[id]). However, I'm unsure how to retrie ...