Subscribe

Vanilla JavaScript Stop Form Submit

โœ๏ธ

In this code tutorial we will learn how to stop a form from submitting with pure Vanilla JavaScript.

8 Jul, 2020 ยท 2 min read

Let's say we want to add form validation in JavaScript. To do the validation, we first need to stop the form from submitting.

We can do this very simply in JavaScript. Follow the next steps of the tutorial to learn how.

HTML Structure

<form onsubmit="return validate();" novalidate>
  <input type="text" name="name" id="name" placeholder="Your name?" required />
  <br /><br />
  <input type="text" name="leave" placeholder="Leave me" />
  <br /><br />
  <input type="submit" value="Send" />
</form>

As you can see we use the on submit function and say to return a function callback. Then we have two fields of which we will validate the first one.

JavaScript Stop Form Submit

To prevent the form submission we use the following JS code:

function validate() {
  const name = document.getElementById('name');
  if (name && name.value) {
    return true;
  } else {
    alert('Please fill the name field');
    return false;
  }
}

We use the return values, either true or false, depending on whether someone filled out the name field.

We could even use event.preventDefault() on the onsubmit function, but this will cause any action not to become true. Hence it hinders our validation after we stopped the form.

That would work well if we plan an AJAX post however.

Find the example code in this Codepen

See the Pen Vanilla JavaScript Stop Form Submit by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

TypeORM viewEntity

30 Mar, 2022 ยท 5 min read

TypeORM viewEntity

The Record Utility Type in TypeScript

12 Mar, 2022 ยท 3 min read

The Record Utility Type in TypeScript

Join 1372 devs and subscribe to my newsletter