The form validation in Bootstrap 5 seems to be having some trouble triggering

Here is the form setup for allowing users to change their account password:

                        <div class="signup-form-small">
                            <form method="post" name="frmPassword" id="frmPassword" class="needs-validation" novalidate>
                                <div class="form-group">
                                    <div class="col form-floating">
                                        <input type="password" class="form-control" id="curpwd" name="curpwd" required>
                                        <label class="form-label" for="curpwd">Your Current Password</label>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col form-floating">
                                        <input type="password" class="form-control" id="newpwd" name="newpwd" required>
                                        <label class="form-label" for="newpwd">Enter New Password</label>
                                    </div>
                                </div>
                                <div class="row form-group">
                                    <div class="col form-floating">
                                        <input type="password" class="form-control" id="cnfpwd" name="cnfpwd" required>
                                        <label class="form-label" for="cnfpwd">Confirm New Password</label>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <button type="submit" id="btnPwdSubmit" name="btnPwdSubmit" class="btn btn-primary btn-lg btn-block w-100 has-spinner">
                                        <div class="spinner-border float-right hidden" id="pwdspinner" role="status"></div>
                                        Change My Password
                                    </button>
                                </div>
                            </form>
                        </div>

The script block below should handle validation for the form:

        $(document).ready(function () {
            'use strict';
            window.addEventListener('load', function () {
                var forms = document.getElementsByClassName('needs-validation');
                var validation = Array.prototype.filter.call(forms, function (form) {
                    form.addEventListener('submit', function (event) {
                        if (form.checkValidity() === false) {
                            event.preventDefault();
                            event.stopPropagation();
                        }
                        form.classList.add('was-validated');
                    }, false);
                });
            }, false);

        });

Here is the script code that runs when the user clicks the 'Change My Password' button in the form:

            $('#frmPassword').submit(function (event) {
                event.preventDefault();

                setPwdDisabled();

                var obj = Object.fromEntries(new FormData(event.target));
                if (obj.Is_Body_HTML == 1) {
                    obj.Is_Body_HTML = true;
                }
                else {
                    obj.Is_Body_HTML = false;
                }
                if (obj.Is_Active == 1) {
                    obj.Is_Active = true;
                }
                else {
                    obj.Is_Active = false;
                }

                if ($('#curpwd').val() != $('#cnfpwd').val()) {
                    $('toastPwd').toast('show)');
                    return;
                }
                var json = JSON.stringify(obj);

                var request = $.ajax({
                    url: "../handlers/changepwd.ashx",
                    method: "POST",
                    data: json,
                    dataType: "json"
                });

                request.done(function (msg) {
                    if (msg.Success == false) {
                        $('#spnPwdErr').html(msg.Status);
                        $('#toastPwdFail').toast('show');
                    }
                    else
                        $('#toastPwdSuccess').toast('show');
                });

                request.fail(function (jqXHR, textStatus) {
                    $('#spnPwdErr').html('Unable to complete your request at this time.');
                    $('#toastPwdFail').toast('show');
                });

                request.always(function (jqXHROrData, textStatus, jqXHROrErrorThrown) {
                    setPwdEnabled();
                });
            });

However, despite the setup, the form validation does not work and the submission happens anyway. No errors or messages are shown in the console. Can anyone provide insight into why this is happening?

Answer №1

It is best to eliminate the add event listener within the jQuery ready function as it serves no purpose in this context.

$(document).ready(function () {
            'use strict';
            var forms = document.getElementsByClassName('needs-validation');
            var validation = Array.prototype.filter.call(forms, function (form) {
                form.addEventListener('submit', function (event) {
                    if (form.checkValidity() === false) {
                        event.preventDefault();
                        event.stopPropagation();
                    }
                    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

Having trouble implementing server-side rendering with Styled-Components in Next JS

I attempted to resolve my issue by reviewing the code and debugging, but unfortunately, I couldn't identify the root cause. Therefore, I have posted a question and included _document.js, _app.js, and babel contents for reference. Additionally, I disa ...

Query in progress while window is about to close

I'm attempting to trigger a post query when the user exits the page. Here's the code snippet I am currently working with: <script type="text/javascript> window.onbeforeunload = function(){ var used = $('#identifier').val(); ...

Should we retain the express variable for a specific purpose?

Being a developer who is still learning the ropes, I fail to understand the necessity of creating or retaining the express variable in an express/Node app. Instead of following this conventional approach: const express = require('express'); con ...

Group a set of x elements together within a div, and then group a distinct number of elements together after every x-grouping

Is there a way to achieve a looping structure like this? For instance: Group every 2 divs into a new div, then (after every 2nd grouping) group every 3 divs together <div id="container"> <div></div> <div></div> ... </div& ...

How can I programmatically close the Date/Time Picker in Material UI Library?

Is there a way to programmatically close the Date/Time Picker in Material UI Library? ...

Issue with ExtJS causing store to not load properly

I have been working on this issue for over a week now and cannot seem to get it resolved. The webservice is returning data, which I can see, but the store is not loading it correctly. The only time I managed to display the entire response in the grid was w ...

I'm having trouble grasping the issue: TypeError: Unable to access the 'subscribe' property of an undefined object

I've been working on a feature that involves fetching data from API calls. However, during testing, I encountered some errors even before setting up any actual test cases: TypeError: Cannot read property 'subscribe' of undefined at DataC ...

What are the steps for building modules using Vuex and fetching data using mapState()?

I've been experimenting with separating my Vuex code into modules, but I'm having trouble retrieving data using mapState(). What's the most effective approach for creating modules and utilizing mapping? Here's the structure of my stor ...

Pulling the month name based on a specific year and week using Javascript

In my HTML form, there are two fields called Year and Week. When the user chooses a Year and Week from the dropdowns, I would like to show the corresponding Month Name for that specific year and week. Is there anyone who can assist me in retrieving the m ...

execute the function whenever the variable undergoes a change

<script> function updateVariable(value){ document.getElementById("demo").innerHTML=value; } </script> Script to update variable on click <?php $numbers=array(0,1,2,3,4,5); $count=sizeof($numbers); echo'<div class="navbox"> ...

Modifying array elements in JavaScript without explicit instructions

I am relatively new to Javascript and seem to be encountering a rather puzzling issue that I'm unable to resolve. Currently, I have two classes: Country and PPM_Data. The Country class contains parameters such as name, area, ppm, etc., along with a f ...

Tips for optimizing the sequencing of 3 ajax requests, with the output of one request serving as input for the subsequent two requests

I'm currently working on a solution for chaining 3 ajax calls where the result of one call feeds into the next two. Here's the scenario: // Invoke the ajax calls firstAjax('mypage.gng','john-doe').then(secondAjax, thirdAjax) ...

Adjust the CSS for the "a" tag's "title" attribute

I am using jquery.fancybox to create an image modal on my website. I have noticed that I can add a description using the title attribute. However, when the description is too long, the text is displayed on a single line and some of it disappears. How can ...

Change a reactive variable based on an event

I am currently working on a file upload feature in my application. Template.uploadFile.events({ 'change .set-file': function ( event, template ) { var file = event.currentTarget.files[0]; [...] } }); My goal is to read each row fro ...

How can we change a jQuery document click function to an inline onclick function?

Under certain circumstances, I have to refactor my click function into a standalone function and trigger it using inline onClick="myFunction();" This is my current code structure: $(document).on('click','.exBtn', function(){ var ex = ...

The issue with the jQuery Mobile onclick event is that it fails to remove the ui-disabled

Ever since I delved into coding with jQuery Mobile, I've noticed a change in the function that once effortlessly removed the "ui-disabled" class. Now, all it does is display an alert message... Snippet from the HTML code: <div data-role="navbar ...

What steps are involved in uploading data to serve as a filter while running a PHP script to retrieve data from an SQL database?

Currently, I am retrieving data from a PHP file using miniAjax. The code snippet below demonstrates how the process begins: microAjax("genjsonphp.php", function(data) { var json = JSON.parse(data); var points = json; //code continues In the c ...

Obtain data from an external XML source using jQuery

Hey there! I'm looking to scrape/parse some information from an external XML file hosted on a different domain and display it on my website. I attempted the following but unfortunately, it didn't work as expected: jQuery(document).ready(functio ...

Obtaining a variable from HTML and passing it to Node.js

Currently, I am utilizing express to handle form submissions. Within my HTML file, there are 20 inputs with unique ids such as address1, address2, address3, and so on. In my node js code, I access these input values using req.body.address1. Users have th ...

What could be the reason for this XSS script not making a request to my server?

Currently diving into the realm of XSS attacks to enhance my knowledge on application security. My goal is to extract the user's cookie from a local website and then transmit it to my local server for testing purposes. I've successfully obtained ...