Solution 1 :

Use form onsubmit

<form onsubmit="return validateEmail(document.getElementById('EmailAddress'))"
    id="form" class="form" action="" method="POST">

And, in this case, validateEmail should return false when the form should not be submitted. Which is the case.

Even though I would move the document.getElementById('EmailAddress') inside the validateEmail method and not pass it through parameter.

Problem :

I am using a function to validate emails in a form. The function works fine as it does return an error message when a user types an invalid email address and leaves the field box. However, even if the email is not valid, they could still submit the form.

How can I prevent that from happening?

// Email validation and error message
function validateEmail(emailField) {
 var reg = /^([A-Za-z0-9_-.])+@([A-Za-z0-9_-.])+.([A-Za-z]{2,4})$/;

 if (reg.test(emailField.value) == false) {

  errorEmail.innerText = 'Looks like this is not an email';
  return false;
  // e.preventDefault();

  errorEmail.innerText = "";
  return true;
<form id="form" class="form" action="" method="POST">
        <input id="FirstName" type="text" placeholder="First Name" name="FirstName" />
        <input id="LastName" type="text" placeholder="Last Name" name="LastName" />

        <!-- This is to show an error when email is not validated -->
        <div id="error-Email"></div>
        <input id="EmailAddress" type="text" placeholder="Email Address" onblur="validateEmail(this);"
          name="EmailAddress" />
        <input id="Password" type="password" placeholder="Password" name="Password" />
        <input onclick="update()" id=" submit" type="submit" value="Claim your free trial" name="Submit" />


Comment posted by jeprubio


Comment posted by

Comment posted by tshimkus

The form will always post if you don’t intercept the default action. There are a lot of ways you can do this. The

Comment posted by

There are several options and many helpful resources available. Check out MDN:

Comment posted by How to prevent form from being submitted?

Does this answer your question?

Comment posted by Quentin

That won’t work. The

Comment posted by jeprubio

Too quick, I forgot the return, my fault, thanks

Comment posted by Hesam Alavi

@jeprubio that did prevent the form from submitting which is great, however, if the user clicks the submit button before doing anything else, the error now shows, whereas I would like the error (“this is not an email”) to only come when the user attempts to type in the email field, and does not type in a valid email.

Comment posted by jeprubio

@HesamAlavi Sorry, I was sleeping. Have you removed