Nanfeng

Notes on software development, code, and curious ideas

Validating an Email Address with a TypeScript Regular Expression

The following TypeScript example uses a regular expression to check whether a string has a common email-address format:

1
2
3
4
5
6
7
8
const email = "example@email.com";
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

if (emailRegex.test(email)) {
console.log(`${email} is a valid email address`);
} else {
console.log(`${email} is not a valid email address`);
}

The expression requires some non-whitespace characters before @, a domain after it, and a dot followed by another non-empty segment. Calling test() returns a Boolean indicating whether the string matches.

This is a practical format check, not proof that the address exists or can receive mail. Real email syntax has many edge cases, so production systems should normally combine lightweight client-side validation with a confirmation email.

+