Preventing a form submission in JavaScript

If necessary, you can prevent the form from being submitted. This is done through the already known to you preventDefault. Let's look at an example.

Let's say we have the following form:

<form action="/handler/" method="POST"> <input name="test1"> <input name="test2"> <input type="submit"> </form>

Get a reference to it into a variable:

let form = document.querySelector('form');

Form submission can be caught via the submit event:

form.addEventListener('submit', function() { });

Let's prevent form submission now:

form.addEventListener('submit', function(event) { event.preventDefault(); });

Given a form with an input. When you try to submit the form, check that a correct email is entered in the input. If this is not the case, prevent the form submission and display a message about it.