Home > Web Front-end > JS Tutorial > How to Validate Email Addresses Using JavaScript Regular Expressions?

How to Validate Email Addresses Using JavaScript Regular Expressions?

Patricia Arquette
Release: 2025-01-01 14:46:11
Original
606 people have browsed it

How to Validate Email Addresses Using JavaScript Regular Expressions?

How to Validate an Email Address in JavaScript

Validating user input as an email address is crucial to prevent errors when sending data to servers or emails. JavaScript offers a convenient method for email address validation using regular expressions.

Regular expressions provide a powerful way to match and validate email addresses. A commonly used regular expression is:

const validateEmail = (email) => {
  return String(email)
    .toLowerCase()
    .match(
      /^(([^<>()[\]\.,;:\s@"]+(\.[^<>()[\]\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    );
};
Copy after login

This expression matches email addresses that adhere to the following criteria:

  • Contains a local part (portion before the @ sign) that consists of letters, numbers, dots, dashes, or underscores.
  • Contains a domain part (portion after the @ sign) that comprises a hostname followed by an optional port number.
  • Allows for quoted addresses (e.g., "example@domain.com").
  • Matches addresses with Unicode characters.

While relying on client-side validation alone is not recommended due to the possibility of JavaScript being disabled, it can provide a first line of defense. Here's an example of validating email addresses using JavaScript:

const validateEmail = (email) => {
  return email.match(
    /^(([^<>()[\]\.,;:\s@"]+(\.[^<>()[\]\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
  );
};
Copy after login

This validation function can then be used in a form or on user input fields to provide instant feedback on email address validity.

The above is the detailed content of How to Validate Email Addresses Using JavaScript Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template