Check out the new Bootstrap 5 form when it's successfully validated

I need to execute some JavaScript if my form is valid. I am using Bootstrap 5 and found this code, but I am unsure how to add 'if form.is_valid {}'

<script>
(function () {
'use strict'
const forms = document.querySelectorAll('.requires-validation')
Array.from(forms)
  .forEach(function (form) {
    form.addEventListener('submit', function (event) {
    if (!form.checkValidity()) {
        event.preventDefault()
        event.stopPropagation()
    }

    if (form.valid(){ # but this not working } else { #this working }

    // already tried using .valid , .is_valid, .isValid but no one work
  
      form.classList.add('was-validated')
    }, false)
  })
})()
</script>

I also came across this snippet:

<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aec4dfdbcbdcd783d8cfc2c7cacfdac7c1c0ee9f809f97eef1f9e407">[email protected]</a>/dist/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0aab1b5a5b2b9edb6a1aca9a4a1b4a9afae80f1eef100f811">[email protected]</a>/dist/additional-methods.js"></script>

function validate_form2(form_id){
        var form = $( "#" + String(form_id) );
        form.validate();
        $( "button" ).click(function() {
            if (form.valid()){
                loading_screen()
                form.submit()
            }
        });
        
    }

However, the issue with using that code is that the message 'Please fill out this field' appears inside the input field rather than as a tooltip.

Thank you!

Answer №1

After thorough investigation, I have discovered a solution: form.checkValidity can be used to verify the validity of a form.

<script>
(function () {
'use strict'
const forms = document.querySelectorAll('.requires-validation')
Array.from(forms)
  .forEach(function (form) {
    form.addEventListener('submit', function (event) {
    if (!form.checkValidity()) {
        event.preventDefault()
        event.stopPropagation()
    }

    // the solution lies within this section
    else { implement your task here }

    
  
      form.classList.add('was-validated')
    }, false)
  })
})()
</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

What is the proper way to utilize variables in package.json with npm version 7.x.x?

I am looking to utilize npm scripts to access keys found in the directories section. "directories": { "client": "client", "server": "server" }, "scripts": { "test:client&qu ...

can you explain the concept of a backing instance in react?

Although the concept of a "backing instance" is frequently mentioned in React documentation, I found it difficult to grasp its meaning. According to the React docs: In order to interact with the browser, you need a reference to a DOM node. By attaching ...

Execute button click automatically upon page loading in AngularJS

I'm trying to figure out how to automatically trigger a button click on an AngularJS page when the page loads based on a querystring value. In a traditional asp.net web forms page, I could easily handle this scenario by calling Button1_Click(sender,e) ...

Employing global variables in JavaScript files with Vue3

In my Vue3 project, I have defined global variables like this: app.config.globalproperties.$locale = locale A composable function has been created to dynamically retrieve these global variables: import { getCurrentInstance ) from 'vue' export f ...

Reveal the inner workings of functions within the Vuex Plugin

I am currently working on setting up a Vuex plugin where I want to make the undo function accessible for use in my component's click events. // plugin.js const timeTravel = store => { // .. other things function undo () { store.commit(&a ...

Tips for showcasing all values in a nested array

In my Vue application, I am dealing with a nested array where users can select one date and multiple times which are saved as one object. The challenge I am facing now is how to display the selected date as a header (which works fine) and then list all the ...

Swap out all hyperlinks on the webpage with a different URL

I am looking to update all links in a specific style with new ones. I want to streamline the download process for Google Drive links. https://drive.google.com/file/d/1cCIWJMBOX-NvzYVTQajaVo5lNknYA2E8/view?usp=sharing My plan is to extract '1cCIWJMBO ...

Save and retrieve documents within an electron application

Currently, I am developing an application that will need to download image files (jpg/png) from the web via API during its initial run. These files will then be stored locally so that users can access them without requiring an internet connection in the fu ...

"Enhance Your Website with jQuery Mobile's Multi-Page Setup and Panel

I am currently facing the challenge of managing multiple pages within a single document and I would like to utilize jQM 1.3's Panel widget to control navigation between these pages. However, the issue arises from the requirement that Panels must be co ...

Tips for choosing or unselecting a row within a Table utilizing the Data Grid Mui

Is it possible to implement row selection and deselection in Mui without using the checkboxSelection prop? I am looking for a way to achieve this functionality in @mui/x-data-grid when clicking on a row. Below is the code snippet from the Table Component ...

Troubleshooting PhantomJS hanging with WebdriverJS tests on Windows

I am currently using webdriverjs to run automated tests on a Windows 8 system. The tests run successfully when the browser is set to Chrome, but encounter issues when I switch to PhantomJS. Interestingly, the same tests run smoothly on OS X Mavericks. Ins ...

Create a boolean flag in Java using JavaScript

Hey there, I'm working on a project where I need to detect the user's browser in JavaScript. For Safari browsers, I have to download an audio file, while for every other browser I need to play the audio. Currently, my code can correctly identify ...

Showing both SubTotal and Total simultaneously in a JavaScript powered interface

Recently diving into Javasript, I came across the code snippet below from a different source that I tweaked to suit my needs. My goal is to show the subtotal in the third column for each benefit while displaying the total of the entire form. However, I&apo ...

Enhancing Numerical Visuals: Tips for Optimizing Visualization of Proximate Numbers using

In my chart, I noticed that the values are very close together such as: Value A -> 3.7747199435 Value B -> 3.775531821 Value C -> 3.7754975674 Value D -> 3.8358619466 Value E -> 3.8856710034 and as a result, the visualization shows minima ...

Error encountered: Javascript throws an error while trying to initialize the Bootstrap datetimepicker if the input value only

My requirement is to utilize the DateTime Picker plugin and load only the Time picker component. To achieve this functionality, I have initialized my input field in the following manner, allowing only time selection: jsfiddle: <div class="input-group ...

Tips for passing a variable containing an image source from Node.js to a Jade file

Below is the code snippet from my index.js file, where I'm using express for routing: var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res){ var db = req.db; ...

Utilizing AJAX and PHP for seamless communication, retrieve and authenticate HTTPS SSL CERTIFICATE when interacting

Recently, I successfully created a node.js REST server located at . To develop the front-end, I am utilizing a combination of html, javascript, and php. However, when I attempted to implement an SSL certificate on the front-end, a problem arose: An issue ...

A guide on utilizing ClassName to insert new items into a DIV

Original HTML code: <span class="specLink"> <specialty><a title="Plastic Surgery" href="link2.aspx">Plastic Surgery</a></specialty> </span> <br /> <span class="specLink"> <specialty2><a titl ...

Maintaining checkbox state using fetch arrays

Included below is the code present on my site, pulling data for each season including numbers of home wins, win percentage, and win lsp. It functions correctly by creating a new table row for each season. Furthermore, there are two columns featuring filte ...

Discovering when the DOM has finished rendering in AngularJS with ng-repeat

I am looking for a way to trigger an alert or message upon completion of rendering in my HTML DOM using AngularJS, specifically when dealing with multiple ng-repeats. HTML Code: <body> <div ng-controller="Ctrl"> <div ng-repeat= ...