5

Im using bootstrap 4 form. any one know how to add correctly passwords doesn't match validation. Thanks

  // Check if passwords match
    $('#pwdId, #confirmPassword').on('keyup', function () {
        if ($('#newPassword').val() != '' && $('#confirmPassword').val() != '' && $('#confirmPassword').val() == $('#confirmPassword').val()) {
       
        }
    });




// Example starter JavaScript for disabling form submissions if there are invalid fields
    (function() {
        'use strict';
        window.addEventListener('load', function() {
            // Fetch all the forms we want to apply custom Bootstrap validation styles to
            var forms = document.getElementsByClassName('needs-validation');
            // Loop over them and prevent submission
            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);
    })();
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">


<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></script>


<form class="form-signin needs-validation" novalidate><div class="card shadow-sm">
    <div class="card-body">
  


        <div class="form-group">
            <label class="sr-only" for="oldPassword">Current Password</label>
            <input class="form-control form-control-sm" id="oldPassword" name="password" placeholder="Current Password"
                   required
                  type="password" autocomplete="off"  aria-describedby="inputGroupPrepend">
            <div class="invalid-feedback">
                Please enter current password.
            </div>
        </div>

        <div class="form-group">
            <div class="form-group">
                <label class="sr-only" for="newPassword">New Password</label>
                <div class="input-group">

                    <input type="password"   autocomplete="off"  class="form-control form-control-sm" id="newPassword" placeholder="New Password" aria-describedby="inputGroupPrepend" required>
                    <div class="invalid-feedback">
                        Please enter new password.
                    </div>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="sr-only" for="confirmPassword">Confirm Password</label>
            <div class="input-group">

                <input type="password"   autocomplete="off"  class="form-control form-control-sm" id="confirmPassword" placeholder="Confirm Password" aria-describedby="inputGroupPrepend" required>
                <div class="invalid-feedback">
                    Password not a match.
                </div>
            </div>
        </div>



    <button id="submitBtn"  class="btn btn-md btn-primary btn-block" type="submit">Update</button>
  
    </div></div>
</form>
core114
  • 5,155
  • 16
  • 92
  • 189

2 Answers2

5

You need to add one line of code into the opening form tag.

<form class="form-signin needs-validation" novalidate oninput='confirmPassword.setCustomValidity(confirmPassword.value != newPassword.value ? true : false)'>

I have made a codepen. Please check that.

https://codepen.io/subhojitghosh/pen/JjROMLO

Reference: https://stackoverflow.com/a/53065577/10850734

Subhojit Ghosh
  • 257
  • 3
  • 10
  • Nice answer! Your code also works if I replace `"Passwords do not match."` by `"Mismatch."` Can we use any string if the values do not match eachother? – edesz Jan 09 '21 at 20:51
  • 1
    @edesz I have updated my code. In oninput we need to return true or false value – Subhojit Ghosh Jan 11 '21 at 14:55
  • Just want to add that I have to specifiy an empty string for the validation to be valid (instead of using false). It seems that the setCustomValidity field accepts a string. https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/setCustomValidity – MarkusAfricanus Oct 19 '21 at 15:25
2

I simplified your validation logic and used disabled and hidden HTML's attributes. You can see the refactored code working here in codesandbox

JS code:

// To ensure the following JS code is executed when the DOM is ready to be manipulated by JS
$(document).ready(function () {
  $("#newPassword, #confirmPassword").on("keyup", function () {
    // store the `newPassword` and `confirmPassword` in two variables
    var newPasswordValue = $("#newPassword").val();
    var confirmPasswordValue = $("#confirmPassword").val();

    if (newPasswordValue.length > 0 && confirmPasswordValue.length > 0) {
      if (confirmPasswordValue !== newPasswordValue) {
        $("#password-does-not-match-text").removeAttr("hidden");
        $("#submitBtn").attr("disabled", true);
      }
      if (confirmPasswordValue === newPasswordValue) {
        $("#submitBtn").removeAttr("disabled");
        $("#password-does-not-match-text").attr("hidden", true);
      }
    }
  });
});

and slightly changed your HTML to this:

<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
  integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
  crossorigin="anonymous"
/>

<script
  src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
  integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
  crossorigin="anonymous"
></script>
<script
  src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"
  integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
  crossorigin="anonymous"
></script>
<script
  src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js"
  integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s"
  crossorigin="anonymous"
></script>
<script src="./index.js"></script>

<form class="form-signin needs-validation" novalidate>
  <div class="card shadow-sm">
    <div class="card-body">
      <div class="form-group">
        <label class="sr-only" for="oldPassword">Current Password</label>
        <input
          class="form-control form-control-sm"
          id="oldPassword"
          name="password"
          placeholder="Current Password"
          required
          type="password"
          autocomplete="off"
          aria-describedby="inputGroupPrepend"
        />
        <div class="invalid-feedback">Please enter current password.</div>
      </div>

      <div class="form-group">
        <div class="form-group">
          <label class="sr-only" for="newPassword">New Password</label>
          <div class="input-group">
            <input
              type="password"
              autocomplete="off"
              class="form-control form-control-sm"
              id="newPassword"
              placeholder="New Password"
              aria-describedby="inputGroupPrepend"
              required
            />
            <div class="invalid-feedback">Please enter new password.</div>
          </div>
        </div>
      </div>
      <div class="form-group">
        <label class="sr-only" for="confirmPassword">Confirm Password</label>
        <div class="input-group">
          <input
            type="password"
            autocomplete="off"
            class="form-control form-control-sm"
            id="confirmPassword"
            placeholder="Confirm Password"
            aria-describedby="inputGroupPrepend"
            required
          />
          <div class="invalid-feedback">Password not a match.</div>
        </div>
      </div>

      <p id="password-does-not-match-text" class="text-danger" hidden>
        Your new password does not match
      </p>

      <button
        id="submitBtn"
        class="btn btn-md btn-primary btn-block"
        type="submit"
        disabled
      >
        Update
      </button>
    </div>
  </div>
</form>

Matthew Barbara
  • 3,792
  • 2
  • 21
  • 32