简体   繁体   English

bootstrap 4验证禁用提交按钮,直到表单验证

[英]bootstrap 4 validation disable submit button until form validated

In the following example of my problem I have 2 fields needing to be validate.在我的问题的以下示例中,我有 2 个字段需要验证。
Until all (2 in this case) fields are validated, the submit button should be disabled.在验证所有(本例中为 2 个)字段之前,应禁用提交按钮。
If both are validated it should be enabled.如果两者都经过验证,则应启用它。

My problem: The minute the first field is validated - the button is enabled, which is too early.我的问题:验证第一个字段的那一刻 - 启用按钮,这为时过早。
I understand (ot think that I do) that this occurs because of where I placed $("#submitBtn").attr("disabled",false);我理解(不认为我这样做)这是因为我放置$("#submitBtn").attr("disabled",false);

Any hint of how to get it work would be greatly appreciated.任何有关如何使其工作的提示将不胜感激。

EDIT: For an example of a full registration form with the submit button enabled ONLY when all the form's elements are validated, see this .编辑:有关仅在验证所有表单元素时启用提交按钮的完整注册表单的示例,请参阅this

<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">
            <input type="text" class="form-control" pattern="^[a-z]{3,6}$" required autofocus>
            <div class="valid-feedback">Valid</div>
            <div class="invalid-feedback">a to z only (3 to 6 long)</div>
          </div>
          <div class="form-group">
            <input type="text" class="form-control" pattern="^[a-z]{3,6}$" required>
            <div class="valid-feedback">Valid</div>
            <div class="invalid-feedback">a to z only (3 to 6 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>
    window.addEventListener('load', function() {
      let currForm1 = document.getElementById('myForm1');
      // 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');
            $("#submitBtn").attr("disabled",false);           <<<<======== ??????
          } else {
            input.classList.remove('is-valid')
            input.classList.add('is-invalid');
          }
        });
      });
      // Validate on submit:
      currForm1.addEventListener('submit', function(event) {
        if (currForm1.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        }
        currForm1.classList.add('was-validated');
      }, false);
    });
  </script>

Inside your input event listener check if all the inputs have an is-valid class.在您的输入事件侦听器中检查所有输入是否具有is-valid class。 If all your inputs have an is-valid class, turn off the disabled button.如果您的所有输入都具有is-valid class,请关闭禁用按钮。

currForm1.querySelectorAll('.form-control').forEach(input => {
  input.addEventListener(('input'), () => {
    if (input.checkValidity()) {
      input.classList.remove('is-invalid')
      input.classList.add('is-valid');
      // $("#submitBtn").attr("disabled",false);           <<<<======== ??????
    } 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);
  });
});

I don't know this is good approach or not and it also depend on your requirement if it fulfil your need so that's fine..我不知道这是否是好方法,它是否满足您的需求也取决于您的要求,所以没关系..

here i'm removing some line and adding some line在这里我删除一些行并添加一些行

  1. remove disable button code from first condition and added at the last从第一个条件中删除禁用按钮代码并在最后添加

 if(input.checkValidity() && index ===1) { $("#submitBtn").attr("disabled", false); }
 <:DOCTYPE html> <html lang="en"> <head> <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"> <input type="text" class="form-control" pattern="^[az]{3,6}$" required autofocus> <div class="valid-feedback">Valid</div> <div class="invalid-feedback">a to z only (3 to 6 long)</div> </div> <div class="form-group"> <input type="text" class="form-control" pattern="^[az]{3:6}$" required> <div class="valid-feedback">Valid</div> <div class="invalid-feedback">a to z only (3 to 6 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> window,addEventListener('load'. function() { let currForm1 = document;getElementById('myForm1'): // Validate on input. currForm1.querySelectorAll('.form-control'),forEach((input. index) => { input,addEventListener(('input'). () => { if (input.checkValidity()) { console.log(input;checkValidity()). input.classList.remove('is-invalid') input.classList;add('is-valid'). } else { input.classList.remove('is-valid') input.classList;add('is-invalid'). } if(input.checkValidity() && index ===1) { $("#submitBtn"),attr("disabled"; false); } }); }): // Validate on submit. currForm1,addEventListener('submit'. function(event) { if (currForm1.checkValidity() === false) { event;preventDefault(). event;stopPropagation(). } currForm1.classList;add('was-validated'), }; false); }); </script> </body> </html>

We need to check if all the other inputs are also valid before assuming that we can just enable it在假设我们可以启用它之前,我们需要检查所有其他输入是否也有效

let currForm1 = document.getElementById('myForm1');
      // Validate on input:
      currForm1.querySelectorAll('.form-control').forEach(input => {
        input.addEventListener(('input'), () => {
          if (input.checkValidity()) {
            /* IF IT PASSES WE NEED TO CHECK THE OTHER INPUTS */

            /* STORE ALL THE INPUTS THAT PASS THE CHECKVALIDITY */
            let allValid = currForm1.querySelectorAll('.form-control').filter(input => 
              { return input.checkValidity() })

            /* WE CAN NOW UPDATE THE SUBMIT BASED ON THE NUMBER OF VALID 
               INPUTS WE HAVE */
            $("#submitBtn").attr("disabled", allValid.length === currForm1.querySelectorAll('.form-control').length); 

            input.classList.remove('is-invalid')
            input.classList.add('is-valid');   
          } else {

            /* IF IT FAILS WE DONT NEED TO CHECK WE WANT THE VALIDATOR AS FALSE */
            $("#submitBtn").attr("disabled", true); 
            input.classList.remove('is-valid')
            input.classList.add('is-invalid');
          }
        });
      });

      /* FINALLY WE CAN UPDATE THE SUBMIT, BASED ON OUR VARIABLE */
      $("#submitBtn").attr("disabled", validatorForSubmit ); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM