Validate Email Address in TypeScript
Q: Create a TypeScript function that checks whether a given string is a valid email address, based on a specified pattern or validation library.
- TypeScript
- Senior level question
Explore all the latest TypeScript interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create TypeScript interview for FREE!
Here's an example of a TypeScript function that checks whether a given string is a valid email address based on a specified pattern:
function isValidEmail(email: string): boolean { // Regular expression pattern for email validation const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return pattern.test(email); } // Usage example const email = '[email protected]'; const isValid = isValidEmail(email); console.log(`Is email valid? ${isValid}`);
In this example, the isValidEmail function takes a string email as input and uses a regular expression pattern to validate whether it is a valid email address. The pattern ^[^\s@]+@[^\s@]+\.[^\s@]+$ ensures that the email address has the correct format, with a non-empty local part, an @ symbol, a non-empty domain part, and a valid top-level domain.
The function returns true if the email address is valid according to the pattern, and false otherwise.
In the usage example, we define an email variable with a test email address ([email protected]). We then call the isValidEmail function with this email and store the result in the isValid variable. Finally, we log the result to the console.
Note: The regular expression pattern used in this example is a basic one and may not cover all possible email address formats. For more robust email validation, you can consider using a validation library or a more comprehensive regular expression pattern.


