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

How Can I Validate Email Addresses Using JavaScript Regular Expressions?

Linda Hamilton
Release: 2024-12-26 10:40:11
Original
801 people have browsed it

How Can I Validate Email Addresses Using JavaScript Regular Expressions?

Email Validation with Regular Expressions in JavaScript

To prevent erroneous user input, JavaScript allows for the validation of email addresses before attempting to send them to a server or attempting to send an email to them.

The most reliable approach for verifying an email address in JavaScript is to use regular expressions. The following regular expression accepts ASCII characters:

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

For unicode support, a more comprehensive regex can be used:

const re =
  /^(([^<>()[\]\.,;:\s@"]+(\.[^<>()[\]\.,;:\s@"]+)*)|(".+"))@(([^<>()[\]\.,;:\s@"]+\.)+[^<>()[\]\.,;:\s@"]{2,})$/i;
Copy after login

However, it's crucial to remember that JavaScript validation shouldn't be depended on alone. Client-side validation is easily bypassed. Server-side validation is also necessary.

Here's an example of JavaScript email validation on the client side:

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,}))$/
  );
};

const validate = () => {
  const $result = $('#result');
  const email = $('#email').val();
  $result.text('');

  if(validateEmail(email)){
    $result.text(email + ' is valid.');
    $result.css('color', 'green');
  } else{
    $result.text(email + ' is invalid.');
    $result.css('color', 'red');
  }
  return false;
}

$('#email').on('input', validate);
Copy after login

In this example, a button is used to trigger the validation and display the result.

The above is the detailed content of How Can I 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