Last active
August 4, 2021 14:03
-
-
Save gaelgthomas/ffce33c4d7ea22e5e2c35f99964801cf to your computer and use it in GitHub Desktop.
Example of an Email Validation with JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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