JavaScript Examples: validate email using regex
// Example JavaScript code to demonstrate how to use regex to validate email addresses
// Function to validate email address using regex
function validateEmail(email) {
// Define the regular expression for validating an email
// The regex pattern explained:
// ^ asserts position at start of the string
// [a-zA-Z0-9._%+-]+ matches one or more of the allowed characters before the @
// @ matches the literal @ symbol
// [a-zA-Z0-9.-]+ matches one or more of the allowed characters for the domain part
// . matches the literal dot symbol
// [a-zA-Z]{2,} matches two or more alphabetic characters for the top-level domain
// $ asserts position at the end of the string
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/;
// Test the email against the regex pattern
const isValid = emailRegex.test(email);
// Log the regex pattern used for validation
console.log("Regex Pattern: ", emailRegex);
// Log the email being tested and whether it is valid
console.log("Testing Email: ", email);
console.log("Is Valid: ", isValid);
return isValid;
}
// Example email inputs to test the validation function
const testEmails = [
"test@example.com", // Valid email
"user.name@domain.co", // Valid email
"invalid-email@", // Invalid email (missing domain part)
"@example.com", // Invalid email (missing local part)
"user@domain@domain.com", // Invalid email (multiple @ symbols)
"user@domain.c", // Invalid email (top-level domain too short)