Implementing Rule for Password Matching in Bootstrap 4 Form Validation

I am utilizing Bootstrap 4 / JS form validation (https://getbootstrap.com/docs/4.0/components/forms/#custom-styles) and it is functioning as expected.

Currently, I am working on implementing the same style and submission rules for comparing two password fields, namely password ('#pw') and repeat password ('#pwRepeat'), so that a green border and checkmark icon are displayed when they match, and a red border and error icon when they do not match.

The issue I am facing is in triggering the invalid format or manually setting it to invalid when the passwords do not match (refer to the comments below for corresponding lines).

Could someone guide me on the correct way to achieve this and provide a brief explanation?

My JavaScript code:

(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) {
                var pw = document.getElementById('pw').value; // $('#pw').val();
                var pwRepeat = document.getElementById('pwRepeat').value; // $('#pwRepeat').val();

                if(pwRepeat != pw) {
                    // Set cell border color to red and display error icon for invalid input
                    pwRepeat.addClass('invalid'); // Not working
                }
                if(form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');    

                // Submit if no errors were found
                if((pwRepeat == pw) && (form.checkValidity() === true)) {
                    // Perform necessary actions
                }

            }, false);
        });
    },
    false);
})();

Thank you in advance,
Tim

Answer №1

There are a couple of issues that need to be addressed in this code snippet.

var pwRepeat = document.getElementById('pwRepeat').value;

The variable pwRepeat is a value, not an element, so the method addClass cannot be used on it.

pwRepeat.addClass('invalid');

To fix this issue, replace the above code with:

document.getElementById('pwRepeat').classList.add("invalid");

Since there is no working example provided, this solution is untested. However, it should give you a starting point to troubleshoot why the current code is not functioning correctly.

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

Why does the UseEffect hook in next.js result in 2 fetch requests instead of the expected 1?

I am encountering an issue where my code is triggering two requests to my API using the GET endpoint. Unfortunately, my understanding of useEffect() is not deep enough to pinpoint where the problem lies. I want to avoid putting unnecessary strain on the ...

Issue: Generated fewer hooks than anticipated. This situation could be a result of an unintentional premature return statement

view image description see image here I encountered an issue while trying to retrieve a specific item from my customer list on the first attempt. The strange behavior occurs when I search for a name not present in the table, then search for an existing en ...

Executing a JavaScript function

I am currently working on an ASP webpage and I am facing an issue with writing JavaScript within it. My goal is to assign a variable to the response of a function that is stored in the code behind (page.aspx.vb). Here is an example of what I am attemptin ...

Trapping an anchor tag event in asp.net

I am currently working on a menu bar using HTML code (I am unable to use asp link buttons). <ul> <li><a href="#"><span>Reconciliation</span></a> <ul> ...

The confusing case of jQuery's e.preventDefault: Unable to submit form despite preventing default behavior

Objective: Prevent the 'submit' button from functioning, validate fields, generate popover alerts for results, and submit form upon closing of popover. To achieve this, I have set up a hidden popover div. When the submit button is clicked, I uti ...

Is it better to use Asynchronous or Synchronous request with XMLHttpRequest in the Firefox Extension for handling multiple requests

As a newcomer to developing Firefox Add-Ons, my initial project involves calling an external API in two steps: Step 1) Retrieve data from the API. Step 2) Use the data retrieved in Step 1 to make another call to the same API for additional information. ...

Unable to retrieve $_POST data using $.post requests while iterating through options with .each

Using the .each method, I constructed an options string and sent it via .post to an external script. clicked.closest("form").find("input,textarea").each(function(){ var input=$(this); if(index==1){ options = ...

Center align list items while concealing any overflow

I'm attempting to arrange a series of avatars side by side without wrapping to the next line, creating a layout similar to this: After exploring Stackoverflow for advice, I came across the following threads: How to keep <li> elements on sing ...

Tips for pinpointing the root cause of a function call

This question may seem strange, but I need to distinguish between these two scenarios. Firstly, I have a function: function calculatePerDayRentCost(){ //body } and I am calling this function in two ways: Firstly, programmatically: $('#qtyExtraDri ...

The div is not displaying the conditional styling as expected

I need help with mapping an array of cards wrapped in a div. I want the first, second, second-to-last, and last divs to go on a new line or take up the entire row. My project is in Vue3 and I'm using the PrimeVue component library. <div class=" ...

JavaScript's connection to the CSS property visibility seems to be causing some issues

The Javascript code seems to be ignoring the CSS display property, even though it's set in the style sheet. I added a debugger statement and noticed that the display value was empty. I've been staring at this for some time now, so I must be overl ...

By invoking the connect() function in Mongoose.js, you can establish several connections to a MongoDB database

In my Node.js Express app, I am establishing a single connection to MongoDB using Mongoose: var express = require('express'); var mongoose = require('mongoose'); mongoose.connect('localhost', 'test'); After definin ...

Guide on Creating a Smooth jQuery Scroll Animation from Top to Bottom and Bottom to Top for a Landing Page Navigation Menu

I'm in the process of developing a landing page website where my navigation links smoothly scroll to different sections on the page. Currently, when I click on a nav link, it instantly takes me to the bottom and then back to the top. However, I want t ...

Enhancing Form Validation with Vuejs 2

With vue-validator being prepared for Vuejs 2, what is the most effective method for implementing frontend validation? UPDATE I've come across a fantastic plugin called Vee Validate ...

What is the definition of XLLS?

Is there a connection between the "XLLS" expression and AJAX / Javascript? What is the actual meaning of XLLS? Thank you in advance. including text from a comment in response ...when I searched for an answer on Google, all I found was Excel XLLs but no ...

Can anyone share tips on how to effectively center navbar link items with Bootstrap?

I recently tried to center the navigation links on my website using Bootstrap. I followed the instructions on the w3schools documentation and also watched a YouTube video for additional guidance. Both resources suggested adding the justify-content-center c ...

Ways to verify the header (h1, h2, h3) attribute of a DOM element

In JavaScript or jQuery, I have a reference to a link. How can I determine if it is an <h1>, <h2>, or another type of heading element? ...

The collapsible toggle feature is currently not working as intended

I have tried looking for solutions but have not been successful. My apologies for asking what may seem like a simple question. The toggle button is not expanding to show the menu items when clicked. It works fine on the "home" page but not on the linked pa ...

Toggle visibility of div content when hovering over a link by leveraging the data attribute, with the div initially visible

I have a collection of links: <p><a href="#" class="floorplan initial" data-id="king"><strong>King</strong></a><br> 4 Bedrooms x 2.5 Bathrooms</p> <p><a href="#" class="floorplan" data-id="wood">< ...

Instructions on calling a function with AngularJS ng-click in a template rendered by a Grails controller

Is there a way to invoke a function using angularjs ng-click on a template that is rendered from a grails controller? I have tried, but the jQuery function call seems to work fine while the ng-click() function does not. What am I missing here? I'm rea ...