Enhancing user registration with Bootstrap 4 validation, ensuring password confirmation and disabling submit button until form is successfully validated

There are 3 input fields in a simple form, each with its own regex pattern.
The 'Password' and 'Confirm Password' fields must match. If they don't, a message "Not Matching" is displayed. If they do, "Valid" is displayed.

I am trying to figure out how to use JavaScript to force the Bootstrap 4 validation to display a red border and 'X' icon in the following scenario:

If I enter 'aa' in the 'Password' field (which matches the regex), it shows a valid green border and a 'V' icon.
Then if I enter 'aa' in the 'Confirm Password' field (also matching the regex), it again shows a valid green border and 'V' icon.
But when I add another character to 'Confirm Password', it immediately displays "Not Matching", even though according to the regex it should still be green with a 'V' icon.

https://i.sstatic.net/c2NZy.jpg

I need help forcing the red border and 'X' icon to appear in this case.

Here is my code:

<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">
        ...
      </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>
    $(document).ready(function(){
      // Check if passwords match
      ...
      });
    </script>

Thank you!

Answer №1

Why not simply switch the is-invalid class on and off as required for both password inputs?

 $('#pwdId, #cPwdId').on('keyup', function () {
        if ($('#pwdId').val() != '' && $('#cPwdId').val() != '' && $('#pwdId').val() == $('#cPwdId').val()) {
          $("#submitBtn").attr("disabled",false);
          $('#cPwdValid').show();
          $('#cPwdInvalid').hide();
          $('#cPwdValid').html('Valid').css('color', 'green');
          $('.pwds').removeClass('is-invalid')
        } else {
          $("#submitBtn").attr("disabled",true);
          $('#cPwdValid').hide();
          $('#cPwdInvalid').show();
          $('#cPwdInvalid').html('Not Matching').css('color', 'red');
          $('.pwds').addClass('is-invalid')
        }
 });

 <form action="page2.php" id="myForm1" class="needs-validation" novalidate>
      <div class="form-group">
        Field1<input type="text" class="form-control" pattern="^[a-z]{2,4}$" required autofocus>
        <div class="valid-feedback">Valid</div>
        <div class="invalid-feedback">a to z only (2 to 4 long)</div>
      </div>
      <div class="form-group">
        Password<input type="text" id="pwdId" class="form-control pwds" pattern="^[a-z]{2,4}$" required>
        <div class="valid-feedback">Valid</div>
        <div class="invalid-feedback">a to z only (2 to 4 long)</div>
      </div>
      <div class="form-group">
        Confirm Password<input type="text" id="cPwdId" class="form-control pwds" pattern="^[a-z]{2,4}$" required>
        <div id="cPwdValid" class="valid-feedback">Valid</div>
        <div id="cPwdInvalid" class="invalid-feedback">a to z only (2 to 4 long)</div>
      </div>
      <div class="form-group">
        <button id="submitBtn" type="submit" class="btn btn-primary submit-button" disabled>Submit</button>
      </div>
 </form>

Demo:

Answer №2

Thanks to @Zim for guiding me through the initial steps, I was able to successfully tackle the problem.

Below is the complete code for a Registration form that includes password comparison functionality.

Please note that the Submit button will only be enabled when all form elements are valid!

Note 1: While I have extensively tested this solution, there may still be potential bugs or design flaws (do inform us if you uncover any).

Note 2: Given my limited experience in Javascript and JQuery (only 2 weeks old), I acknowledge that there might be more elegant solutions available (feel free to suggest improvements).

Here is the full code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"><title>Registration</title>
  <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" style="background-color: lightblue;">
        <form action="page2.php" id="myForm1" class="needs-validation" novalidate>
          <h1 class="text-center">Registration</h1><hr>
          <div class="form-group">
            First Name<input name="myInput" id="fisrtNameId" type="text" class="form-control" pattern="^[a-z]{2,15}$" required autofocus>
            <div class="valid-feedback">Valid</div>
            <div class="invalid-feedback">a to z only (2 to 15 long)</div>
          </div>
         <!-- Code truncated for brevity -->
        </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>
 <!-- JavaScript section omitted for conciseness -->
</body>
</html>

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

No input value provided

I can't figure out what's going wrong. In other js files, this code works fine. Here is my HTML code: <table class='table'> <tr> <th>Event</th><td><input class='for ...

Implementing callback within another function: A guide

I'm embarking on the journey of creating a node waterfall using the async module. I've just dipped my toes into the waters of asynchronous programming in node. Essentially - how do I trigger callback() within the http.request function to proceed ...

Can components be nested within other components using http-vue-loader?

Trying to incorporate Vue components within components without utilizing webpack for practical reasons is my current challenge. I have opted to use http-vue-loader for loading the vue files into my project. Thus far, I have successfully created vue files ...

What are the best ways to incorporate a theme into your ReactJS project?

Looking to create a context for applying dark or light themes in repositories without the need for any manual theme change buttons. The goal is to simply set the theme and leave it as is. Currently, I have a context setup like this: import { createContext ...

Is it possible to achieve a fade effect in material-ui that truly hides the component instead of just disabling its visibility? If so, how can this be accomplished?

Currently, I am utilizing the component provided by material-ui, which can be found at material-ui. <Fade in={!randomizeFlag}> <Grid> <FormControlLabel control={<Switch onChange={this.handleStartValueFlag} & ...

Changing the background color of MUI TextField for autocomplete suggestions

I am currently facing an issue with the background color of auto-complete fields in my React.js and Material UI app. https://i.sstatic.net/lZdDh.png The auto-complete fields are adding a white background which is unnecessary. Interestingly, when I manua ...

Controlling a complex IF statement with jQuery

Currently, I have an if statement with over 100 different conditions. Right now, I am using a structure similar to this... $('select').on("change",function(){ if( $(this).val() === 'tennis' ) { $('.sport').val( ...

Autocomplete component fails to trigger onChange event upon losing focus in Mui framework

When using a Mui Autocomplete with the properties of multiple and freeSolo, a situation arises where pressing Return triggers an onChange event. However, when tabbing out of the Autocomplete widget, the typed text remains without updating the state of the ...

Cannot retrieve Global variables when using chrome.tabs.executescript in Chrome 55

After recently updating Chrome to version 55.0.2883.75, I encountered an issue with my self-developed Chrome Plugin used for parsing HTML files. In the plugin, I utilize chrome.tabs.executescript to retrieve data from a background HTML page. Previously, I ...

Initializng an array with null values in Javascript

Can you explain why this Javascript code: var myArray = new Array(3); does not produce the same result as: var otherArray = [null, null, null]; ? Keep in mind that (myArray == otherArray) returns false. Additionally, is there a way to create an ...

Automatically redirect dynamic URLs to the home page in NextJS

In my NextJS project, I've set up a dynamic page that retrieves and displays blog content. The URL for this page is as follows: https://example.com/blog/[blogId] However, when attempting to access this URL on the production site, instead of landing o ...

Why is my jQuery animation running so sluggishly everywhere? Is there a way to improve its performance and make

I attempted to replicate the slider effect seen on this website: Below is the animation code: $('.tagLink').click(function () { $('html').css('overflow', 'hidden'); $('#tagBoxOverlay&ap ...

Sending an HTTP post request with form data and various field controls will not be directed to a Java backend

Recently, I've started working with AngularJs and I'm facing an issue with uploading image files along with their labels through a Jax-RS post rest API. My problem is that the control in my AngularJS controller is not entering the Java post API. ...

The issue of the window.open method malfunctioning on Internet Explorer 9

Struggling to make it work in IE9: Note: I forgot to mention that $variable is coming from a $_GET request based on a drop down menu selection. I am currently offline, <a href="#" onclick="window.open('https://domain.com/contact-form?chatq=& ...

Efficiently transferring property values

In my current code, I have functions that retrieve specific properties from an object within an array. Since each object in the array has multiple properties, I find myself using separate functions to extract different properties. This approach is not eff ...

Send a bundle of data through AJAX requests

An issue has been encountered on an HTML/PHP page named sucessful.php where a variable job_id passed from another page is not being received by the destination page interview.php. The problem arises when attempting to transfer two variables and their corr ...

Assigning values to props in a Vue component

I created a Vue component that is supposed to receive the "uploadedFile" prop, but it's not functioning properly. I am only getting the correct information in the $attrs: https://i.sstatic.net/crXmH.png Here is my component: Vue.component('t ...

Swiper V7 React is experiencing issues with numerous parameters not functioning properly

Here is the code snippet I have been working on: I am currently exploring the Swiper library documentation to understand its functionalities better. import React from "react"; // Direct React component imports import { Swiper, SwiperSlide } fro ...

Learn the simple steps to duplicate events using ctrl, drag, and drop feature in FullCalendar v5 with just pure JavaScript

My goal is to incorporate CTRL + Drag & Drop functionality in FullCalendar v5 using nothing but pure JavaScript. I delved into the topic and discovered that this feature has been discussed as a new UI feature request on the FC GitHub repository. There ...

Switch from using jQuery to vanilla JavaScript for handling POST requests

I am looking to eliminate the jQuery dependency and use plain JavaScript instead in the code below for a post request. <script type="text/javascript> $(function() { $.post("test_post.php", { name: "John Doe", ...