Check if email is valid
A valid email address typically follows this format:
Where:
localpart
is the part before the@
symbol, which can contain letters, numbers, and special characters (except for spaces and punctuation marks).domain
is the part after the@
symbol, which is usually a domain name (e.g.,example.com
).tld
is the top-level domain (e.g.,.com
,.org
,.net
, etc.).
Here are some common rules to check if an email address is valid:
- Local part:
- Must be at least 1 character long.
- Can contain letters (a-z, A-Z), numbers (0-9), and special characters (!, #, $, %, ^, &, *, _, -, +, =, ~, `).
- Can't contain spaces or punctuation marks (except for the
@
symbol).
- Domain:
- Must be at least 2 characters long.
- Can contain letters (a-z, A-Z), numbers (0-9), and special characters (-,.).
- Can't contain spaces or punctuation marks (except for the
.
symbol).
- TLD:
- Must be a valid top-level domain (e.g.,
.com
,.org
,.net
, etc.). - Can't contain spaces or punctuation marks.
- Must be a valid top-level domain (e.g.,
Using these rules, you can write a simple function to check if an email address is valid:
function isValidEmail(email) {
const re = /^[a-zA-Z0-9!#$%&*+-/_=~-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
return re.test(email);
}
This regular expression checks if the email address matches the format described above. If it does, the function returns true
, otherwise it returns false
.
You can test this function with some examples:
console.log(isValidEmail("[email protected]")); // true
console.log(isValidEmail("example@example")); // false (missing TLD)
console.log(isValidEmail("[email protected]")); // false (invalid domain)
console.log(isValidEmail("[email protected]")); // false (invalid domain)
console.log(isValidEmail("example@example!com")); // false (invalid local part)
Keep in mind that this is a basic validation and may not cover all possible edge cases. For more advanced validation, you may want to use a dedicated email validation library or service.