javascriptjqueryformsvalidationsubmission

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


I am creating a single-page website where a contact form loads when a user clicks the "Contact Me" button. The default content <div class="container profile"> is hidden and the form <div class="container form-container"> is revealed.

I have managed to implement some form validation, but even after the alert messages, the form field disappears as though the form was submitted successfully. How do I prevent the form from submitting and returning back to the main screen IF the fields have not been filled out?

Thanks for your help!

<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>

Solution

  • Return false in your validation function

    // 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;
     }
    }
    

    and check your validation is successful or not

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