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="https://formspree.io/mzbdlwlb" 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" />
</form>