Validation in Bootstrap form does not appear when browser saved data is utilized

When data is saved in the browser, the bootstrap validation (green tick) does not display, but it works perfectly when the data is entered manually.

<!doctype html>
<html lang="en">
<head>
  <!-- Required meta tags and Bootstrap CSS -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Registration Form</title>
  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="15777a7a61666167746555203b263b26">[source]</a>/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    /* Optional: Adjust form width on larger screens */
    .registration-form {
      max-width: 500px;
      margin: auto;
    }

    /* Remove autofill background color in Chrome */
    input:-webkit-autofill {
    -webkit-box-shadow: 0 0 0 1000px white inset !important; /* Changes background to white */
    -webkit-text-fill-color: #000 !important; /* Ensures text remains black */
  }
  </style>
</head>
<body>

<div class="container mt-5">
  <div class="registration-form">
    <div class="card">
      <div class="card-body">
        <h3 class="card-title text-center mb-4">Register</h3>
        <form class="needs-validation" novalidate>
          <!-- First Name and Last Name -->
          <div class="row">
            <div class="col-md-6 mb-3">
              <label for="firstName" class="form-label">First Name</label>
              <input type="text" class="form-control" id="firstName" pattern="^[A-Za-z]+$" placeholder="First Name" required>
              <div class="invalid-feedback">
                Please enter your first name (letters only).
              </div>
            </div>
            <div class="col-md-6 mb-3">
              <label for="lastName" class="form-label">Last Name</label>
              <input type="text" class="form-control" id="lastName" pattern="^[A-Za-z]+$" placeholder="Last Name" required>
              <div class="invalid-feedback">
                Please enter your last name (letters only).
              </div>
            </div>
          </div>
          <!-- Email -->
          <div class="mb-3">
            <label for="emailAddress" class="form-label">Email</label>
            <input type="email" class="form-control" id="emailAddress" placeholder="Email" required>
            <div class="invalid-feedback">
              Please enter a valid email address.
            </div>
          </div>
          <!-- Password -->
          <div class="mb-3">
            <label for="password" class="form-label">Password</label>
            <input type="password" class="form-control" id="password" minlength="6" placeholder="Password" required>
            <div class="invalid-feedback">
              Please enter a password with at least 6 characters.
            </div>
          </div>
          <!-- Confirm Password -->
          <div class="mb-3">
            <label for="confirmPassword" class="form-label">Confirm Password</label>
            <input type="password" class="form-control" id="confirmPassword" minlength="6" placeholder="Confirm Password" required>
            <div class="invalid-feedback">
              Passwords do not match.
            </div>
          </div>
          <!-- Terms and Conditions -->
          <div class="form-check mb-3">
            <input type="checkbox" id="terms" class="form-check-input" required>
            <label class="form-check-label" for="terms">I agree to the terms and conditions</label>
            <div class="invalid-feedback">
              You must agree to the terms and conditions.
            </div>
          </div>
          <!-- Submit Button -->
          <div class="d-grid">
            <button class="btn btn-primary" type="submit">Register</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<!-- Bootstrap JS and custom validation script -->
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="54363b3b20272026352414617a677a67">[source]</a>/dist/js/bootstrap.bundle.min.js"></script>
<script>
(() => {
  'use strict';

  // Fetch all the forms we want to apply custom Bootstrap validation styles to
  const forms = document.querySelectorAll('.needs-validation');

  // Trigger validation for autofilled fields on page load
  const triggerAutofillValidation = () => {
    const autofillFields = document.querySelectorAll('input:-webkit-autofill');

    // Dispatch an input event for each autofilled field to trigger validation
    autofillFields.forEach(field => {
      field.dispatchEvent(new Event('input', { bubbles: true }));
    });
  };

  // On window load, trigger autofill validation
  window.addEventListener('load', triggerAutofillValidation);

  // Loop over each form and prevent submission if invalid
  Array.from(forms).forEach(form => {
    // Password and Confirm Password fields
    const password = form.querySelector('#password');
    const confirmPassword = form.querySelector('#confirmPassword');

    // Event listener to validate password match
    confirmPassword.addEventListener('input', function () {
      if (confirmPassword.value !== password.value) {
        confirmPassword.setCustomValidity('Passwords do not match');
      } else {
        confirmPassword.setCustomValidity('');
      }
    });

    // Form submission event
    form.addEventListener('submit', event => {
      // Check for validity
      if (!form.checkValidity()) {
        event.preventDefault();
        event.stopPropagation();
      }

      // Add Bootstrap validation classes
      form.classList.add('was-validated');
    }, false);

  });
})();
</script>

</body>
</html>  

Please refer to the images below for more information:

Manually Entered Data

Browser Saved Data

I am looking to have the green tick displayed even when using browser saved data. What steps should I take to achieve this?

Answer №1

I came across a discussion on Github regarding this topic: https://github.com/twbs/bootstrap/issues/39530

In my research, I stumbled upon this link: (CAUTION ADVISED DUE TO HIGH VOLUME OF NOTIFICATIONS!)

The website provides insights into the issue:

This bug revolves around Bootstrap's validation styles causing issues with the browser's autofill feature for form fields. Essentially, applying the .was-validated class to a <form> element hinders the proper restoration of saved data by the browser.

A solution could be to temporarily remove the .was-validated class from the <form> element using JavaScript and then reapplying it after the autofill event occurs.

Answer №2

After researching, it appears that the issue lies in the user agent stylesheet setting the background-image to none !important, making it impossible to override. This results in our background image not displaying when users select saved data. According to MDN documentation, changing this is not a simple task. For more information, you can visit: developer.mozilla.org/en-US/docs/Web/CSS/:autofill

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

Sharing data between Javascript files without relying on a database can be accomplished through the use of import and export

Attempting to create a login page in react without relying on traditional JavaScript proved to be a challenging task for me. In order to access the necessary data, I had to manually export my JavaScript file where the relevant information was stored and ap ...

Prevent fixed element from scrolling beyond a specific point

I'm working on a fixed sidebar that needs to scroll along with the main content and stop at a specific point when scrolling down, and vice versa when scrolling up. I've created a script that calculates the window height, current scroll position ...

Using Typescript to assign a new class instance to an object property

Recently, I crafted a Class that defines the properties of an element: export class ElementProperties { constructor( public value: string, public adminConsentRequired: boolean, public displayString?: string, public desc ...

Guide for utilizing a table value as a parameter in a mySQL query with PHP

My website features an HTML table that is filled with data pulled from a mySQL table using PHP. Each row in the table is clickable, and when clicked, it opens a modal that contains a form to update and submit data back to the database using a mysql update ...

Leveraging JQuery to retrieve the string value from an onclick() event

Curious if there's a more efficient approach to tackle this issue, decided to seek input from the SO community... There's a third-party web page over which I have no control in terms of how it's displayed, but they do allow me to integrate ...

Automatic refreshing of page at specified intervals

My website allows users to add posts and comments, similar to social media platforms. While everything is working smoothly, I am facing an issue with the auto-update feature. I would like the page to automatically refresh every 20 seconds to display any n ...

Name values not appearing in dropdown list

Looking for some assistance with displaying a list of names in a dropdown menu using Angular. The dropdown is present, but the names from my array are not appearing. I think it might be a simple fix that I'm overlooking. I'm new to Angular, so an ...

Creating resizable images using CSS in Bootstrap

I have a horizontal scrolling page implemented with bootstrap 5. The images all have the same height but varying widths. My objective is for the images to always fill the width of the page, so they should resize accordingly when the browser window size cha ...

Using jQuery to animate the opacity to 0 and then smoothly fade out the element

I am currently working on a function that animates the opacity of an element to 0 as the user scrolls. However, I am facing an issue where the element is fading out too early instead of waiting for the animation to finish. Here is a link to my jsFiddle sho ...

"When trying to access a jQuery ID, it is coming back as undefined even though the

I'm attempting to obtain the ID of a specific element, save it as a variable, and then utilize that ID value to interact with other elements in the same section bearing the identical ID. <div class="mainContent"> <div class="articleContent"& ...

Methods for encoding and decoding special characters using either JavaScript or jQuery

I am looking for a solution to encode and decode various special characters using JavaScript or jQuery... ~!@#$%^&*()_+|}{:"?><,./';[]\=-` I attempted to encode them using the following code snippet... var cT = encodeURI(oM); // ...

I am unable to incorporate the RobotJS module into my ElectronJS project

Currently, I am working on a Windows desktop application using ElectronJS. My main challenge is integrating the RobotJS module into my project. Despite successfully downloading the module with 'npm install robotjs' and incorporating it into my ma ...

The jQuery scroll functionality is malfunctioning

Could you please assist me in resolving an issue with my scroll effects not working? I have been unable to pinpoint the problem. The code snippet I am using is based on Bootstrap 4. Below is the code snippet in question: //SCROLL EFFECT $(".nav-link" ...

Using jQuery to generate a JSON object dynamically based on the values entered in each input field

I'm facing a situation where I need to extract data from a JSON format using PHP. However, I'm struggling with how to structure the Javascript object in order to dynamically create the JSON format. Here is my current scenario: <input title=" ...

Synchronize variables in a single Vue.js file

In my Vue file (version 2.x), I have three fields - input1 x input2 = result. Whenever one of these fields is changed, the other two should update simultaneously. I attempted to use the watch property but it resulted in an infinite loop as the watchers ke ...

Generating HTML content using Angular 8 and JSON data

Currently, I am managing an Angular Storybook that consists of various components. Within the stories.ts file of a component, there is a JSON snippet containing properties such as the content of a DIV element, shown below... { "accordionLink": ' ...

Utilizing flexbox, absolute positioning, and 100% height in web design

While experimenting with a flexbox inside an absolute box within a div of defined height, I encountered a problem. Let me explain the issue step by step. Here is a link to a fiddle demonstrating the problem: https://jsfiddle.net/8ub9tyub/ When hovering o ...

Experiencing difficulties with my .css formatting following the installation of bootstrap in Angular

I've been immersing myself in Angular and encountered an issue that has me stumped. Despite using the latest version of Bootstrap in my Angular project, I'm facing challenges with my styles.css file that was defined prior to installing Bootstrap. ...

JavaScript: Simply returning an array with no elements

As I work on refining a solution for fizzbuzz to generate an array of numbers and strings, I encountered an issue where the return statement only outputs an empty array. Interestingly, when I print the array to the console, it appears as intended with all ...

Is there a way to manipulate each object that I create in Three.js?

Currently, I am working on developing a scene with three.js and incorporating 3 spheres into it. My goal is to switch all wireframe materials of the spheres created to non-wireframe ones. I opted not to use scene.traverse() as my scene contains multiple ...