带密码确认的引导 4 验证并禁用提交,直到表单验证(注册表单)

Posted

技术标签:

【中文标题】带密码确认的引导 4 验证并禁用提交,直到表单验证(注册表单)【英文标题】:bootstrap 4 validation with password confirmation and submit disabled until form validated (Registration form) 【发布时间】:2020-03-05 02:03:23 【问题描述】:

在一个简单的表单中,有 3 个输入字段,每个字段都带有正则表达式。 其中两个(“密码”和“确认密码”)必须匹配。如果不匹配,则会显示消息“不匹配”。如果是,则显示“有效”。

如何(通过 javascript)在以下情况下强制显示 Bootstrap 4 验证的红色边框和“X”图标:

在“密码”字段中输入“aa”(它与正则表达式匹配,因此是有效的绿色边框和 V 图标)。 在“确认密码”字段中输入“aa”(它与正则表达式匹配,因此是有效的绿色边框和 V 图标)。 现在我在“确认密码”中添加了另一个字符,它立即显示“不匹配”,但由于根据正则表达式没问题 - 它仍然是绿色的,带有“V”图标。

发生这种情况时,我需要强制使用红色边框和“X”图标。

我的代码:

      <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">
        <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" 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" 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>
      </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
      $('#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');
         else 
          $("#submitBtn").attr("disabled",true);
          $('#cPwdValid').hide();
          $('#cPwdInvalid').show();
          $('#cPwdInvalid').html('Not Matching').css('color', 'red');
          
        );
      let currForm1 = document.getElementById('myForm1');
        // Validate on submit:
        currForm1.addEventListener('submit', function(event) 
          if (currForm1.checkValidity() === false) 
            event.preventDefault();
            event.stopPropagation();
          
          currForm1.classList.add('was-validated');
        , false);
        // Validate on input:
        currForm1.querySelectorAll('.form-control').forEach(input => 
          input.addEventListener(('input'), () => 
            if (input.checkValidity()) 
              input.classList.remove('is-invalid')
              input.classList.add('is-valid');
             else 
              input.classList.remove('is-valid')
              input.classList.add('is-invalid');
            
            var is_valid = $('.form-control').length === $('.form-control.is-valid').length;
            $("#submitBtn").attr("disabled", !is_valid);
          );
        );
      );
    </script>

谢谢!

【问题讨论】:

【参考方案1】:

您不能根据需要在两个密码输入上切换is-invalid 类吗?

 $('#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>

演示:https://www.codeply.com/p/AQBzIBAsZl

【讨论】:

谢谢。检查您的“codeplay”确实解决了“确认密码”问题,但它增加了“密码”字段的验证。我会尽力解决这个问题并让你知道。再次感谢。【参考方案2】:

在@Zim 的帮助下,我开始并设法解决了它。

以下是完整注册表单的代码以及两个密码的比较。

请注意,只有当表单中的所有元素都有效时,才会启用提交按钮!

注意 1 :我对它进行了广泛的测试,但它可能存在错误或设计缺陷(如果你发现了请告诉我们)。

注意 2:当谈到 Javascript 和 JQuery,我才 2 周前出生,所以我想我的解决方案可能没有那么优雅(再次,让我们都知道如果你能改进它)。

这里是完整的代码:

<!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>
          <div class="form-group">
            Last Name<input name="myInput" id="lastNameId" type="text" class="form-control" pattern="^[a-z]2,15$" required>
            <div class="valid-feedback">Valid</div>
            <div class="invalid-feedback">a to z only (2 to 15 long)</div>
          </div>
          <div class="form-group">
            E-mail<input type="email" name="myInput" id="emailId" class="form-control" pattern="^[a-zA-Z0–9.!#$%&’*+\/=?^_`|~-]+@[a-zA-Z0–9](?:[a-zA-Z0–9-]0,61 [a-zA-Z0–9])?(?:\.[a-zA-Z0–9](?:[a-zA-Z0–9-]0,61[a-zA-Z0–9])?)*$" required>
            <div class="valid-feedback">Valid</div>
            <div class="invalid-feedback">Not a valid email address</div>
          </div>
          <div class="form-group">
            Password<input type="text" id="pwdId" class="form-control" pattern="^[a-z]2,6$" required>
            <div class="valid-feedback">Valid</div>
            <div class="invalid-feedback">a to z only (2 to 6 long)</div>
          </div>
          <div class="form-group">
            Confirm Password<input type="text" id="cPwdId" class="form-control myCpwdClass" pattern="^[a-z]2,6$" required>
            <div id="cPwdValid" class="valid-feedback">Passwords Match</div>
            <div id="cPwdInvalid" class="invalid-feedback">a to z only (2 to 6 long)</div>
          </div>
          <div class="form-group">
            Description<textarea form="myForm1" name="myInput" id="descId" type="text" class="form-control" required></textarea>
            <div class="valid-feedback">Valid</div>
            <div class="invalid-feedback">Required</div>
          </div>
          <div class="form-group">
            <div class="custom-control custom-checkbox">
              <input type="checkbox" id="agreeId" class="custom-control-input form-control" required>
              <label for="agreeId" id="agreeLabelId" class="custom-control-label">Agree to terms <a href="https://www.youtube.com/watch?v=5_nWGG_TFDM" target="_blank"> (terms & conditions)</a></label>
              <div id="agreeValid" class="valid-feedback">Valid</div>
              <div id="agreeInvalid" class="invalid-feedback">Needs to be checked</div>
            </div>
          </div>
          <div class="form-group">
            <button id="submitBtn" type="submit" class="btn btn-secondary" disabled>Register</button>
          </div>
        </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>
  <script>
    $(document).ready(function()
      // ----------- Set all elements as INVALID --------------
      var myInputElements = document.querySelectorAll(".form-control");
      var i;
      for (i = 0; i < myInputElements.length; i++) 
        myInputElements[i].classList.add('is-invalid');
        myInputElements[i].classList.remove('is-valid');
      
      // ------------ Check passwords similarity --------------
      $('#pwdId, #cPwdId').on('keyup', function () 
        if ($('#pwdId').val() != '' && $('#cPwdId').val() != '' && $('#pwdId').val() == $('#cPwdId').val() ) 
          $('#cPwdValid').show();
          $('#cPwdInvalid').hide();
          $('#cPwdInvalid').html('Passwords Match').css('color', 'green');
          $('.myCpwdClass').addClass('is-valid');
          $('.myCpwdClass').removeClass('is-invalid');
          $("#submitBtn").attr("disabled",false);
          $('#submitBtn').addClass('btn-primary').removeClass('btn-secondary');
          for (i = 0; i < myInputElements.length; i++) 
            var myElement = document.getElementById(myInputElements[i].id);
            if (myElement.classList.contains('is-invalid')) 
              $("#submitBtn").attr("disabled",true);
              $('#submitBtn').addClass('btn-secondary').removeClass('btn-primary');
              break;
            
          
         else 
          $('#cPwdValid').hide();
          $('#cPwdInvalid').show();
          $('#cPwdInvalid').html('Not Matching').css('color', 'red');
          $('.myCpwdClass').removeClass('is-valid');
          $('.myCpwdClass').addClass('is-invalid');
          $("#submitBtn").attr("disabled",true);
          $('#submitBtn').addClass('btn-secondary').removeClass('btn-primary');
        
      );
      // ----------------- Validate on submit -----------------
      let currForm1 = document.getElementById('myForm1');
      currForm1.addEventListener('submit', function(event) 
        if (currForm1.checkValidity() === false) 
          event.preventDefault();
          event.stopPropagation();
        
        else 
          $("#submitBtn").attr("disabled",false);
          $('#submitBtn').addClass('btn-primary').removeClass('btn-secondary');
          currForm1.classList.add('was-validated');
        
      , false);
      // ----------------- Validate on input -----------------
      currForm1.querySelectorAll('.form-control').forEach(input => 
        input.addEventListener(('input'), () => 
          if (input.checkValidity()) 
            input.classList.remove('is-invalid');
            input.classList.add('is-valid');
           else 
            input.classList.remove('is-valid');
            input.classList.add('is-invalid');
          
          var is_valid = $('.form-control').length === $('.form-control.is-valid').length;
          // $("#submitBtn").attr("disabled", !is_valid);
          if (is_valid) 
            $("#submitBtn").attr("disabled",false);
            $('#submitBtn').addClass('btn-primary').removeClass('btn-secondary');
           else 
            $("#submitBtn").attr("disabled",true);
            $('#submitBtn').addClass('btn-secondary').removeClass('btn-primary');
          
        );
      );
      // ------------------------------------------------------
    );
  </script>
</body>
</html>

【讨论】:

以上是关于带密码确认的引导 4 验证并禁用提交,直到表单验证(注册表单)的主要内容,如果未能解决你的问题,请参考以下文章

从按钮引导程序 4 中删除禁用属性

使用引导验证器验证密码并确认密码字段

当 jquery.validate 验证表单时启用提交按钮

使用 UI Utils 进行 Angular 表单验证

验证 Recaptcha 后禁用提交

当引导验证成功时,如何使用 $.post 提交表单而不进行页面重定向?