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

How Can I Validate Email Addresses Using JavaScript?

Linda Hamilton
Release: 2024-12-29 05:40:10
Original
248 people have browsed it

How Can I Validate Email Addresses Using JavaScript?

Validating Email Addresses in JavaScript

To ensure user input is a valid email address, JavaScript provides several validation techniques.

Regular Expressions:

Utilizing regular expressions is an efficient method for email validation. Consider the following expression that matches valid email formats:

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

Unicode Support:

To accommodate unicode characters in email addresses, use the following regular expression:

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

Client-Side Validation:

This JavaScript code demonstrates how to validate email addresses on the client side:

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

function validate() {
  const email = $('#email').val();
  const $result = $('#result');
  $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;
}
Copy after login

Considerations:

Remember that JavaScript validation alone is not sufficient, as it can be disabled by the user. It is crucial to also implement validation on the server side to ensure data integrity.

The above is the detailed content of How Can I Validate Email Addresses Using JavaScript?. 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