Utilizing Bootstrap 5: Executing JavaScript exclusively upon successful form validation

I've created a form with multiple input fields that are being validated using Bootstrap 5 validation.

<form class="needs-validation asset-test" action="{{ url_for('asset_test') }}" method="post" novalidate>
[...]
</form>

As per the documentation, the code below is responsible for the validation:

// Example starter JavaScript for disabling form submissions if there are invalid fields
(() => {
    'use strict'
  
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    const forms = document.querySelectorAll('.needs-validation')
  
    // Loop over them and prevent submission
    Array.from(forms).forEach(form => {
      form.addEventListener('submit', event => {
        if (!form.checkValidity()) {
          event.preventDefault()
          event.stopPropagation()
        }
  
        form.classList.add('was-validated')
      }, false)
    })
  })()

Now I would like to trigger a JavaScript function upon successful form submission:

$('.asset-test').on('submit', function () {
    alert('form submitted');
});

The issue is that this function executes even when some input fields do not pass the validation criteria set by Bootstrap.

I understand that every field needs to have the 'was-validated' class added. Do I need to check each individual input field? My knowledge of JavaScript is limited in this area. Could someone provide guidance on how to achieve this?

I'm looking to only run my JavaScript function if the Bootstrap validation is successful.

Answer №1

To improve form handling, consider including an else statement following the invocation of checkValidity():

// Sample JavaScript code to enhance form validation
(() => {
    'use strict'

    // Select all forms that require customized Bootstrap validation
    const forms = document.querySelectorAll('.needs-validation')

    // Iterate through each form and prevent submission if invalid
    Array.from(forms).forEach(form => {
        form.addEventListener('submit', event => {
            if (!form.checkValidity()) {
                event.preventDefault()
                event.stopPropagation()
                console.log("Form is invalid");
            } else {
                console.log("Form is valid");
                // Insert additional functionality here
            }

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

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

Tips for using the arrow keys to navigate the cursor/caret within an input field

I am trying to create a function that allows the cursor/caret to move inside an input field character by character using the arrow keys (ArrowLeft, ArrowRight) on a keydown event. Current Approach: const handleKeyDown = (e: KeyboardEvent<HTMLInputEle ...

Update the class information using jQuery after performing an action and serialize the button's ID for AJAX requests

I'm facing an issue with two buttons on my page: <td> <button id="1" class="green-button">Publish</button> <button id="1" class="yellow-button">Delete</button> </td> The green-button and red-button have different ...

Issue with rendering Backbone subview correctly

Today, I delved into the world of website development using backbone.js. Surprisingly, after a whole morning of trying to crack a puzzling problem, I find myself stuck. Let me focus on the crucial bits of code here. Initially, I have a View named Navigat ...

Referencing another component in StyledComponents

I'm looking to modify the properties of my parent component's :after selector whenever the child element is focused. It seemed straightforward at first, but for some reason, I just can't seem to make it work. Here's a glimpse of my comp ...

How can you fetch data from a PHP file using AJAX before performing a header redirect?

I am currently in the process of adding more dynamism to my website. I have developed a forum from scratch and now I am integrating JavaScript into it. All the PHP backend work is complete. My next goal is to enable user login without having to refresh the ...

Error encountered: The fiber texture failed to load due to a component becoming suspended during the response to synchronous input

I'm encountering an issue while attempting to load a texture through the TextureLoader: const texture = useLoader(TextureLoader, '/textures/texture.png') The error message I receive from react is as follows: ERROR A component suspended w ...

Modify the color scheme of an HTML webpage

Looking to enhance my HTML page with a new feature. The page is responsive and currently using Bootstrap CSS and JS. My goal is to allow users to change the color of the page dynamically by selecting a background or text color. Check out this example link ...

Add an element to the input field

Two input buttons are available for users to upload files. <input type="file" id="fileUpload" name="files" multiple><br/> <div id="selectedFiles"></div> The selected files will be appende ...

Verify if an express module has a next() function available

Is there a method to check if there is a function after the current middleware? router.get('/', function(req, res, next){ if(next){//always returns true } }); I have a function that retrieves information and depending on the route, thi ...

Configuring Angular to use ES6 syntax

Trying to integrate angular google maps with es6 syntax has been a challenge for me. In es5, the code typically looks like this: .config(function(uiGmapGoogleMapApiProvider) { uiGmapGoogleMapApiProvider.configure({ // key: 'your api key&ap ...

Choosing a particular 2D array based on another variable in jQuery and JavaScript

Within my project, I am utilizing 2D arrays to append specific divs under particular circumstances. In an effort to streamline and enhance the code, I attempted to create a variable that would determine which array to utilize based on the id of an HTML < ...

Tips for testing the setTimeout function within the ngOnInit using Jasmine

Could someone please assist me with writing a test for an ngOnInit function that includes a setTimeout() call? I am new to jasmine test cases and unsure of the correct approach. Any guidance would be greatly appreciated. app.component.ts: ngOnInit(): void ...

What steps do I need to take to retrieve data in a JSON array based on its

Hello, I could really use your assistance with a problem I'm having. Here is the scenario: I have a JSON array that looks like this: "category" : [ { id: 1, product: [{id : product_1, type : ball}] }, { id : 2, product :[{id : prod ...

The perfect approach for loading Cordova and Angularjs hybrid app flawlessly using external scripts

We have developed a single page hybrid app using cordova 3.4.0 and angularJS with the help of Hybrid app plugin(CPT2.0) in visual studio 2013. This app contains embedded resources such as jquery, angularjs, bootstrap, and some proprietary code. Additiona ...

The functionality of the Jquery mobile panel ceases to work properly when navigating between pages within a multi-page

Within a multi-page template setup in a jQuery mobile application, an issue arises after navigating away from the first page using panel navigation. Upon returning to the first page through another form of navigation, the panel appears "hanged." Upon clos ...

How can I use nodejs to retrieve all data fields from a table except for one specific field?

Is there a way to fetch all fields data from a table without specifying the field names or creating a view? I have attempted the following SQL query: WITH orderschema as (SELECT array_to_string(ARRAY(SELECT c.column_name FROM information_schema.co ...

Unlocking the potential of the Bootstrap search dropdown

Currently, I am utilizing the following code to create a searchable dropdown menu. I found helpful guidance in this forum post. I am seeking advice on how to retrieve the value of the selected option. For example, if 'China' is chosen, I would l ...

Angular: Refresh mat-table with updated data array after applying filter

I have implemented a filter function in my Angular project to display only specific data in a mat-table based on the filter criteria. Within my mat-table, I am providing an array of objects to populate the table. The filtering function I have created loo ...

React - Pagination with page number not functioning correctly

Currently, I am trying to set up pagination for my website. When I visit localhost:3000/profile/, it displays the first 3 elements correctly. The pagination also functions properly when I input a number like 3 for ${page}, taking me to page 3 seamlessly. H ...

Revamp your arrays with input fields in Vue3

When presented with two arrays of options, users must select an option from each array. ==> first array: [ orange, green, yellow ] ==> second array: [ orange, green, yellow ] The challenge is to update the second array based on the user's sele ...