How to validate an email address in JavaScript?

September 29, 2022 No comments validate js email tips solutions javascript

Introduction

In JavaScript, we may need to validate an email address.

In this article, we'll present the best way to validate email in JavaScript.

How to validate an email address in JavaScript

The best way to validate an email address in JavaScript is to let the browser do that for us. It saves you from the horror of regular expressions and is not buggy on outdated browsers.

function validateEmail(value) {
  var input = document.createElement('input');

  input.type = 'email';
  input.required = true;
  input.value = value;

  return input.checkValidity();
}

The validateEmail function creates input instance and set the type=email and value=[email address to validate]. Next, we use input.checkValidity() function to check if given email address is correct.

Conclusion

To validate email address in JavaScript we may use the input.checkValidity() function available in modern browsers.

{{ message }}

{{ 'Comments are closed.' | trans }}