Created
November 10, 2022 06:09
-
-
Save 4r7ur-sid/ea9a6b0c9ddd62f9d73067b9af0cbcc9 to your computer and use it in GitHub Desktop.
JavaScript | Function to check if email is valid and cleanup if required
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
/* | |
This function checks if the email is valid and return the email if it is valid or return false if it is not valid | |
If covers all the modern email formats and top level domains. | |
*/ | |
const checkEmail = (email, cleanEmail = false) => { | |
const cleanUp = () => { | |
// Removing all spaces from the email | |
email = email.replace(/\s/g, ''); | |
return email.toLowerCase(); | |
} | |
// Checking if the email is valid | |
const emailRegex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; | |
email = cleanEmail ? cleanUp(email) : email | |
if (emailRegex.test(email)) { | |
return email; | |
} | |
return false; | |
} | |
/* Testing the function | |
console.log(checkEmail('hi@siddharthverma.in')); | |
console.log(checkEmail('Fraud Email')); | |
console.log(checkEmail('Email with spaces @siddharthverma .in')); | |
console.log(checkEmail('hi@sid.black')); | |
With Clean Up | |
console.log(checkEmail('Email with spaces @siddharthverma .in', true)); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment