如果我的表单未通过验证,如何阻止我的页面加载?

How do I prevent my page from loading if my form wasn't validated?

我正在创建一个单页网站,当用户单击 "Contact Me" 按钮时,会加载一个联系表单。默认内容 <div class="container profile"> 隐藏,表格 <div class="container form-container"> 显示。

我已经设法实现了一些表单验证,但即使在警告消息之后,表单字段也消失了,就好像表单已成功提交一样。如果未填写字段,如何防止表单提交并返回主屏幕?

感谢您的帮助!

<body>
  <div class="container profile">
    <div class="row">
      <div class="one-half column" style="margin-top: 10%">
        <h4>TITLE GOES HERE</h4>
        <p>Morbi interdum mollis sapien. Sed ac risus. Phasellus lacinia, magna a ullamcorper laoreet, lectus arcu pulvinar risus, vitae facilisis libero dolor a purus. Sed vel lacus. Mauris nibh felis, adipiscing varius, adipiscing in, lacinia vel, tellus. Suspendisse ac urna. Etiam pellentesque mauris ut lectus. Nunc tellus ante, mattis eget, gravida vitae, ultricies ac, leo. Integer leo pede, ornare a, lacinia eu, vulputate vel, nisl.</p>
        <button class="button-primary">Contact Me</button>
      </div>
    </div>
  </div>

  <!-- This form appears when the "Contact Me" button is clicked. -->
    <div class="container form-container">
      <div class="row">
        <div class="one-half column" style="margin-top: 20%">
          <!-- <div class="close-container"><img class="close" src="close.png"/></div> -->
          <h4>What can I help you with?</h4>
          <form name="contact" method="post">
            <label for="exampleName">Name</label>
            <input class="u-full-width" type="text" placeholder="John Boyega" name="fname" id="exampleName">
            <!-- <div class="row">
              <div class="six columns"> -->
                <label for="exampleEmailInput">Your email</label>
                <input class="u-full-width" type="email" placeholder="youremail@mail.com" name="email" id="exampleEmailInput">
              <!-- </div> -->
              <!-- <div class="six columns"> -->
                <label for="exampleRecipientInput">Reason for contacting</label>
                <select class="u-full-width" name="reason" id="exampleRecipientInput">
                  <option value="Option 1">Web Design</option>
                  <option value="Option 2">User Experience Design</option>
                  <option value="Option 3">Illustration</option>
                  <option value="Option 4">Pixel Art</option>
                  <option value="Option 5">Other</option>
                </select>
              <!-- </div>
            </div> -->
            <label for="exampleMessage">Message</label>
            <textarea class="u-full-width" placeholder="Hey gurl…" name="message" id="exampleMessage" minlength="20" maxlength="2000"></textarea>
            <label class="example-send-yourself-copy">
              <input type="checkbox">
              <span class="label-body">Send a copy to yourself</span>
            </label>
            <input id="submission" class="button-primary" type="submit" value="Submit"></input>
            <button class="close">Cancel</button>
            </form>
        </div>
      </div>
    </div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script>

  // Function that validates the form fields.
  function validateForm() {
    var x = document.forms["contact"]["fname"].value;
    if (x == "") {
      alert("Fill out a name before submission.");
    }
  }
// Function that closes the form when successfully submitted.
  function submitForm() {
    $( ".close").click(function () {
      $('.form-container').hide();
      $('.profile').show();
    });
  }
  // Submit form action.
  $("form").submit(function (e) {
    validateForm();
    if (x == "") {
      e.preventDefault();
    } else {
      submitForm();
    }
  });
    // Button that reveals the contact form.
    $( ".button-primary").click(function () {
      $('.profile').hide();
      $('.form-container').show();
    });

</script>
</body>
</html>

尝试将 e.preventDefault() 放在函数的第一行,然后检查验证。如果请求有效,则执行其余操作。 祝你好运!

你可以选择 e.preventDefault() ,就像这样:

$('#contact').on('submit',function(e){
  let validate_flag = true ; 
  validate_flag= validate_form();
  if(validate_flag==false)
{
  e.preventDefault();
   //TODO:WHAT TO DO WHEN FORM IS NOT VALIDATED
}
else{
   //TODO:WHAT TO DO WHEN FORM IS VALIDATED
}
});

希望它有用:)。让我知道

Return 在你的验证函数中为 false

// Function that validates the form fields.
function validateForm() {
var x = document.forms["contact"]["fname"].value;
if (x == "") {
  alert("Fill out a name before submission.");
  return false;
 }
}

并检查您的验证是否成功

// Submit form action.
$("form").submit(function (e) {
  var validated=validateForm();
  if (validated == false) {
    e.preventDefault();
  } else {
   submitForm();
 }
});