How to Validate Email Address using RegExp in JavaScript? (original) (raw)

Last Updated : 15 Apr, 2025

Validating an email address in JavaScript is essential for ensuring that users input a correctly formatted email. Regular expressions (RegExp) provide an effective and efficient way to check the email format.

Why Validate Email Addresses?

Validating email addresses is important for a number of reasons:

What is a Regular Expression?

A Regular Expression (RegExp) is a sequence of characters that forms a search pattern. In JavaScript, RegExp objects are used for pattern matching within strings, such as checking the format of email addresses. For email validation, we use RegExp to check if an email address follows the general structure of a valid email.

A common RegExp pattern to validate email addresses looks like this:

/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.

Regex Breakdown:

Validating Email Address Format in JavaScript Regex

You can use either the test() method or the match() method with a regular expression to validate an email.

1. Using the test() Method with RegExp

You can use either the test() method or the match() method with the RegExp pattern to validate the email format.

JavaScript `

let regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/; let mail = "test@example.com"; if (regex.test(mail)) { console.log("Valid Email address"); } else { console.log("Invalid Email address"); }

`

2. Using match() with RegExp

Another approach is to use the match() method, which returns an array if the email matches the regular expression or null if it doesn’t.

JavaScript `

//Driver Code Starts let regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/; let mail = "user@domain.com"; //Driver Code Ends

let isValid = mail.match(regex); if (isValid) { console.log("Valid email address"); } else { console.log("Invalid email address"); }

`

Conclusion

Using RegExp in JavaScript is an efficient way to validate email addresses by checking the structure of the email. This ensures the email includes a valid username, the "@" symbol, a valid domain, and a correct TLD (like .com or .org). However, keep in mind that this method only checks the format and doesn't confirm whether the email address is deliverable or belongs to an active account.