Skip to content

Instantly share code, notes, and snippets.

@gaelgthomas
Last active August 4, 2021 14:03
Show Gist options
  • Save gaelgthomas/ffce33c4d7ea22e5e2c35f99964801cf to your computer and use it in GitHub Desktop.
Save gaelgthomas/ffce33c4d7ea22e5e2c35f99964801cf to your computer and use it in GitHub Desktop.
Example of an Email Validation with JavaScript
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Validate Email</h1>
<p>Write your email and we will validate it:</p>
<!-- event.preventDefault() -> avoid the form to reload the page or redirect (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) -->
<form onsubmit="event.preventDefault(); validateMyForm();">
<input type="email" id="email" name="email" placeholder="Email" />
<input type="submit" value="Submit" />
<span id="error"></span>
</form>
</body>
</html>
<script>
// Email validation function
function isEmailValid(email) {
const emailRegexp = new RegExp(
/^[a-zA-Z0-9][\-_\.\+\!\#\$\%\&\'\*\/\=\?\^\`\{\|]{0,1}([a-zA-Z0-9][\-_\.\+\!\#\$\%\&\'\*\/\=\?\^\`\{\|]{0,1})*[a-zA-Z0-9]@[a-zA-Z0-9][-\.]{0,1}([a-zA-Z][-\.]{0,1})*[a-zA-Z0-9]\.[a-zA-Z0-9]{1,}([\.\-]{0,1}[a-zA-Z]){0,}[a-zA-Z0-9]{0,}$/i
)
return emailRegexp.test(email)
}
// Function to validate the form and display an error message
function validateMyForm(event) {
// We fetch the email and error inputs by their ids
const emailInput = document.querySelector('#email');
const errorInput = document.querySelector('#error');
// We validate the email using the "isEmailValid" function
if (!isEmailValid(emailInput.value)) {
// If there is an error, we update the text and set the color to red
error.textContent = "Please enter a valid email"
error.style.color = "red"
} else {
// If the email is valid we display nothing or we remove the error message
error.textContent = ""
}
}
</script>
@Blazing-Mike
Copy link

Thanks man. I would check it out and use for my existing projects I left pending due to form validation issues... I would check for ways to be in it's most optimized form

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment