Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Form Validation Works But Does Not Prevent Form Submission

I use javascript to validate my form input and it works fine but the form still gets submitted when errors are not corrected.

How do I prevent form submission until the user makes corrections?

Sample Code Below;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$('.validate').hide();
$('body').on('blur', '#phone', function() {
  $('.validate').hide();
  isphone($(this).val());
});

function isphone(phone) {
  if (phone === "1234" || phone === "23456") {
    $(".validate").show();

  } else {
    $(".validate").hide();
  }
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

<form action='' method='POST' id="submitForm">

  <input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000" />

  <div class="validate"><span style="color: red;"><b>Phone in use!</b></span></div>

  <button href='/' type='submit' id="submitForm">Process</button>

</form>

>Solution :

To write a helpful answer, I made a small refactor, rewriting isphone to be a reusable validation function that just returns true or false. I renamed it too. Now we can reuse the validation logic in different places.

form elements emit a submit event just before they are actually submitted. We must listen for the sumbit event, and if validation fails, we can return false which will cancel the event, and therefore preventing form submission.

$('.validate').hide();
$('body').on('blur', '#phone', function() {
  var value = $(this).val();
  if (isPhoneInUse(value)) {
    $(".validate").show();
  } else {
    $(".validate").hide();
  }
});
$('#submitForm').on('submit', function(e) {
  var value = $("#phone").val();
  if (isPhoneInUse(value)) {
    // validation failed. cancel the event
    console.log("not submitting");
    return false;
  }
})

function isPhoneInUse(phone) {
  return (phone === "1234" || phone === "23456")
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

<form action='' method='POST' id="submitForm">

  <input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000" />

  <div class="validate"><span style="color: red;"><b>Phone in use!</b></span></div>

  <button href='/' type='submit' id="submitForm">Process</button>

</form>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading