Using HTML5 form validation features but not actually submitting the form

HTML5 form validation is great. Using an attribute like required or minlength, maxlength, etc., you can validate the form without having to write a single line of JavaScript. However, what if you want to use the validation features but don’t want to actually submit the form?

Maybe this is something you would do:

<form id="myForm">
  <input type="text" id="firstName" required>
  <input type="text" id="lastName" required>
  <button id="mySubmitBtn">Submit</button>
</form>
const mySubmitBtn = document.getElementById('mySubmitBtn');
mySubmitBtn.addEventListener('click', e => {
  e.preventDefault();
  // do other stuff here
}

The e.preventDefault() will stop your form from submitting, but it will also not activate HTML form validation. How do we still keep our beloved form validation? The solution is to use the checkValidity() method on the form element.

const mySubmitBtn = document.getElementById('mySubmitBtn');
muSubmitBtn.addEventListener('click', e => {
  if (myForm.checkValidity()) {
    e.preventDefault();
    // do other stuff here
    console.log('do this instead of submitting.')
  }
}

The checkValidity() method returns a true boolean value only if HTML form validation has passed. We don’t have to worry about handling a case in which validation fails since the form does not submit in that case.

Hope this helps!

Leave a Reply

Your email address will not be published. Required fields are marked *