【问题标题】:How to not submit form if there are validation fields outstanding?如果有未完成的验证字段,如何不提交表单?
【发布时间】:2020-03-12 14:07:55
【问题描述】:

我有一个包含一些必填字段的页面。附件文件字段,一些文本框,包括检查电子邮件有效和匹配并确保不为空,并选中一个复选框以确保用户确认条款和条件。

我遇到的问题是,如果我不填写表格并单击“立即购买”,它会执行验证,但会重定向用户结帐。如果表单上有验证,我们如何获得它以便提交按钮不会重定向?我在 html 中使用 required 和一些用于电子邮件验证的 javascript。

HTML 来自

<form id="tcform">    
      <p>
        <b>Attach your CV:</b> (.doc, .docx, .pdf, .txt, .rtf)
        </p>

        <input type="file" id="uploadCV" required/>

        <br/><br/>

        <div class="formcontainer">
        <label for="email"><b>Email:</b></label>
        <input type="input" id="email" name="email"  />

        <p id="resultEmail"></p>


        <label for="email"><b>Confirm Email:</b></label>
        <input type="input" id="confirmEmail" name="confirmEmail"  />

        <p id="resultConfirmEmail"></p>


        <label for="job"><b>Desired Job Position:</b></label>
        <input type="input" id="job" name="job" required />
        </div>

        <br/>
      <p><b>Quantity:</b> 1</p>

      <b class="price">Price:</b> £40
      <button type="submit" class="btn btn-default buynow" 
      id="checkout-button-sku_xxx" role="link">
      Buy Now
    </button>

      <p class="tcparagraph"><i style="font-size:small">Expected Completion Time: Within 10 working days</i></p>
      <p class="tcparagraph"><input id="field_terms" type="checkbox" required name="terms"> I accept the <u><a href="Terms" id="tclink">Terms and Conditions</a></u></p>
      </form>

Javascript

    <script>
      var file = document.getElementById('uploadCV');

    file.onchange = function(e) {
      var ext = this.value.match(/\.([^\.]+)$/)[1];
      switch (ext) {
        case 'doc':
        case 'docx':
        case 'pdf':
        case 'txt':
        case 'rtf':
          break;
        default:
          alert('Please upload a file that matches any of these file types: .doc, .docx, .pdf, .txt, .rtf');
          this.value = '';
      }
    };

    (function() {
      var stripe = Stripe('pk_test_xxxxxxxxxxxxxx');

      var checkoutButton = document.getElementById('checkout-button-sku_xxx');
      checkoutButton.addEventListener('click', function () {
        // When the customer clicks on the button, redirect
        // them to Checkout.
        stripe.redirectToCheckout({
          items: [{sku: 'sku_xxx', quantity: 1}],

          // Do not rely on the redirect to the successUrl for fulfilling
          // purchases, customers may not always reach the success_url after
          // a successful payment.
          // Instead use one of the strategies described in
          // https://stripe.com/docs/payments/checkout/fulfillment
          successUrl: window.location.protocol + '//www.xxx.com/services/cv-rewrite',
          cancelUrl: window.location.protocol + '//www.xxx.com/services/cv-rewrite',
        })
        .then(function (result) {
          if (result.error) {
            // If `redirectToCheckout` fails due to a browser or network
            // error, display the localized error message to your customer.
            var displayError = document.getElementById('error-message');
            displayError.textContent = result.error.message;
          }
        });
      });
    })();

    function validateEmail(email) {
      var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      return re.test(email);
    }

    function validate() {
      var $result = $("#resultEmail");
      var $confirmResult = $("#resultConfirmEmail");
      var email = $("#email").val();
      var confirmEmail = $("#confirmEmail").val();
      $result.text("");

      if (validateEmail(email)) {
        if (email == confirmEmail) {
          $confirmResult.text("");
          return true;
      } else {
        $confirmResult.text("Your email and confirm email do not match");
        $confirmResult.css("color", "red");
      }
        } else {
        $result.text("You have not provided a valid email");
        $result.css("color", "red");

        }

      return false;
    }

    $(".buynow").on("click", validate);

    window.onload = function(){
    var label = document.getElementsByClassName('close');
    for (var i = 0; i<label.length; i++) {
      label[i].onclick = function () {
      var el = (this.parentNode);
      el.parentNode.removeChild(el);
      };
    }
    };        
   </script>

【问题讨论】:

  • 所以在调用条带 api 之前调用验证函数并运行它

标签: javascript html css


【解决方案1】:

您应该在条带重定向之前调用您的 validate 方法,并且您还应该检查表单默认验证 (form.checkValidity()) 以检查您未在 validate 方法中手动检查的内容.

checkoutButton.addEventListener('click', function(event) {
      event.preventDefault();
      
      // When the customer clicks on the button, redirect
      // them to Checkout if validations pass.
      const isFormValid = checkoutButton.form.checkValidity() && validate();

      if (!isFormValid) return; // or show message or whatever else you want

      stripe.redirectToCheckout({
            items: [{
              sku: 'sku_xxx',
              quantity: 1
            }],

            ...

【讨论】:

  • 我认为return false;只有在你使用事件onSubmit时才会生效。在其他事件中,您必须触发提交命令。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-14
  • 2010-10-14
  • 1970-01-01
  • 1970-01-01
  • 2020-09-02
  • 2021-06-27
  • 1970-01-01
相关资源
最近更新 更多