Implement a function to validate an email address using a regular expression.
Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer
Logic/Approach:
1. Use a regular expression that matches common email formats. Note that a perfect, RFC-compliant email regex is extremely complex. A practical one is usually sufficient.
2. Use the test() method of the RegExp object, which returns true if there is a match and false otherwise.
function isValidEmail(email) {
// This regex is a good balance of accuracy and simplicity for most use cases.
// It checks for:
// - one or more characters before the @
// - an @ symbol
// - one or more characters for the domain name
// - a period
// - at least two characters for the top-level domain
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
return emailRegex.test(email);
}
console.log(isValidEmail("test@example.com")); // true
console.log(isValidEmail("test.name+alias@example.co.uk")); // true
console.log(isValidEmail("test@example")); // false
console.log(isValidEmail("invalid-email@")); // false
console.log(isValidEmail("")); // false