Enhance user experience with real-time form validation in Bootstrap 4 as the user inputs

In order to troubleshoot my issue, I created a simple index.php file with 2 input fields and a button that redirects to page2.php.
These input tags have a regex pattern for Bootstrap-4 form validation.

Issue 1: The validation only occurs after clicking the button, not as I type in the inputs.
Issue 2: Upon refreshing without entering any data, the button still redirects me to page2.php.

I suspect that the problem lies with addEventListener('load'), but being new to PHP, JS, Bootstrap, and life in general, I'm not entirely sure...

Any suggestion or idea would be greatly appreciated!

Here is the code snippet:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<style>
  input[type="submit"]:disabled {
    background-color: red;
  }
</style>
</head>

<body>
  <div class="container mt-2">
    <div class="row">
      <div class="col-md-4 offset-md-4">
        <form action="page1.php" id="myForm1" class="was-validation" novalidate>
          <div class="form-group">
            <input type="text" class="form-control" pattern="^[a-z]{3,6}$" autofocus>
            <div class="valid-feedback">Valid.</div>
            <div class="invalid-feedback">a to z only (3 to 6 long)</div>
          </div>
          <div class="form-group">
            <input type="text" class="form-control" pattern="^[a-z]{3,6}$" autofocus>
            <div class="valid-feedback">Valid.</div>
            <div class="invalid-feedback">a to z only (3 to 6 long)</div>
          </div>
          <div class="form-group">
            <button type="submit" class="btn btn-primary">Submit</button>
          </div>
        </form>
      </div>
    </div>
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
  <script>
    (function() {
      window.addEventListener('load', function() {
        let currForm1 = document.getElementById('myForm1');
        currForm1.addEventListener('submit', function(event) {
          if (currForm1.checkValidity() === false) {
            event.preventDefault();
            event.stopPropagation();
          }
          currForm1.classList.add('was-validated');
        }, false);
      });
    })(); 
  </script>

Answer №1

To prevent the form from being submitted with empty inputs, you can use the required attribute on each input field. Here is an example implementation:

window.addEventListener('load', function() {
  let currForm1 = document.getElementById('myForm1');
  currForm1.addEventListener('submit', function(event) {
    if (currForm1.checkValidity() === false) {
      event.preventDefault();
      event.stopPropagation();
    }
    currForm1.classList.add('was-validated');
  }, false);
  // Validate on input:
  currForm1.querySelectorAll('input').forEach((input) => {
    input.addEventListener('input', () => {
      if (input.checkValidity()) {
        input.classList.remove('is-invalid')
        input.classList.add('is-valid');
      } else {
        input.classList.remove('is-valid')
        input.classList.add('is-invalid');
      }
    });
  });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<style>
  input[type="submit"]:disabled {
    background-color: red;
  }
</style>
</head>

<body>
  <div class="container mt-2">
    <div class="row">
      <div class="col-md-4 offset-md-4">
        <form action="page1.php" id="myForm1" class="was-validation" novalidate="z">
          <div class="form-group">
            <input type="text" class="form-control" pattern="^[a-z]{3,6}$" autofocus required>
            <div class="valid-feedback">Valid.</div>
            <div class="invalid-feedback">a to z only (3 to 6 long)</div>
          </div>
          <div class="form-group">
            <input type="text" class="form-control" pattern="^[a-z]{3,6}$" autofocus required>
            <div class="valid-feedback">Valid.</div>
            <div class="invalid-feedback">a to z only (3 to 6 long)</div>
          </div>
          <div class="form-group">
            <button type="submit" class="btn btn-primary">Submit</button>
          </div>
        </form>
      </div>
    </div>
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

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

Identify the index of a list item using a custom list created from buttons

When dealing with a dynamically built list like this: <ul id="shortcuts"> <li><input type="checkbox" value="false"/><button>foo</button><button>-</button></li> <li><input type="checkbox" value ...

Leveraging functions with Ng-Repeat

I am currently dealing with two different arrays of objects. The first array contains a list of permissions groups, while the second array consists of user groups. My main goal is to compare the Group Owner (which is represented by ID 70) with the list of ...

Obtain the final result once all promises have been successfully resolved in a loop

Here is an array of IDs: let idsArray = [1, 2, 3, 4, 5]; How can I ensure that a promise is returned only after all calls made within the loop are completed? let deferredPromise = $q.defer(), finalResult = []; fo ...

When using res.render to send results, redundant lines are displayed

I feel like I must be missing something really obvious, but for the life of me I cannot figure out what it is. All I want to do is list the documents in a MongoDB collection in a straightforward manner. I am working with nodejs, mongoose, and Jade (althoug ...

Adding a dynamic style programmatically to an element created using createElement in Vue: A guide

I have a canvas element that is created programmatically and I am looking to apply a reactive style to it. canvas = document.createElement('canvas') //Apply style this.$refs.parentElement.appendChild(canvas) In a typical scenario, you would u ...

Deleting outdated files in a temporary uploads directory - NodeJS best practices

My process for removing old files from a tmp upload directory involves the code below: fs.readdir( dirPath, function( err, files ) { if ( err ) return console.log( err ); if (files.length > 0) { files.forEach(function( file ) { ...

Issue: The keyword in React/React-Native is returning a boolean value instead of the expected element object

I've recently delved into learning and coding with React, and I'm encountering a bug that I need help fixing. The issue lies within my application screen where I have two checkboxes that should function like radio buttons. This means that when on ...

Using jQuery to choose options and change the background color

Hey there, I have a select box below: <select id="events"> <option value="1" style="background-color:green;">Event 1</option> <option value="2" style="background-color:yellow;">Event 2</option> <option value="3 ...

AngularJS - managing checkboxes and dropdownlists

When I talk about the topic of depending on checkboxes from a dropdown list, I mention that I populate my dropdown list with data from the controller: @RequestMapping(value = "/all", method = GET) public List<Warehouse> findAll(){ return warehous ...

JavaScript - If you change the properties of an object within an array, does it automatically set the array as needing an update?

If we were to imagine a scenario where there is an array containing 3 objects, and then I decide to access the second object by its index in order to modify one or more of its properties, what would happen? Would this modification mark the entire array a ...

Store a collection of objects in an array and assign it to a variable in JavaScript within a React application

Is there a way to loop through this Json data and extract the attribute values into an array for insertion into a constant variable in React? For example: { "data": [ { "id": "1", "type": "vid ...

Improving efficiency for handling a vast number of inputs in React applications

Dealing specifically with Material UI, I am faced with the challenge of rendering a large number of inputs (more than 100) while effectively managing global state. Performance issues arise when using the Material UI <TextField /> component, with noti ...

Error event triggered by Ajax call despite receiving 200 ok response

$.ajax({ url: 'http://intern-dev01:50231/api/language', type: 'GET', dataType: 'json', success: function() { console.log('Success! The call is functioning.'); }, ...

Removing users from a Socket.IO chat room using Node.js

I am facing an issue with removing users from Socket.IO when their browser is closed. The 'user' in the array 'users[]' is not getting removed or updated. Additionally, I would like to update the users on the client side as well. Can so ...

One way to incorporate type annotations into your onChange and onClick functions in TypeScript when working with React is by specifying the expected

Recently, I created a component type Properties = { label: string, autoFocus: boolean, onClick: (e: React.ClickEvent<HTMLInputElement>) => void, onChange: (e: React.ChangeEvent<HTMLInputElement>) => void } const InputField = ({ h ...

What is the proper way to transfer data from a file using npm's request package?

I'm currently utilizing npm's request module to interact with an API. The API specifications require that data be sent through a file using the @site.json notation when making a CURL request. For example: curl -X POST -d @site.json 'https ...

Creating Eye-Catching Images by Incorporating Image Overlays Using Just One Image

I'm facing a bit of a challenge here. I need to figure out how to overlay an image onto another image using just a single image tag. Specifically, I want to add a resize icon to the bottom right corner of an image to let users know they can resize it ...

Is there a way to access the original query string without it being automatically altered by the browser?

I'm currently encountering an issue with query strings. When I send an activation link via email, the link contains a query string including a user activation token. Here's an example of the link: http://localhost:3000/#/activation?activation_cod ...

Utilizing global variables in Vue.js while working with the CLI template

How can I create a global variable in my Vue.js app that is accessible by all components and modifiable by any of them? I am currently utilizing the CLI template. Any recommendations on how to achieve this? Appreciate your assistance. Dhiaa Eddin Anabtaw ...

Efficiently Displaying Multiple HTML Elements in React Native WebView

I am currently working on developing an Epub reader in React Native and facing a challenge. I need to find a way to efficiently transfer multiple html content files from the Epub container to the webview in order to achieve seamless pagination. ...