Fraser Hamilton

How to validate an email address in JavaScript

July 20, 2020

Regular expressions are patterns used to match character combinations in strings. They’re pretty powerful and are commonly used for anything from validating form fields to searching large text documents. Here’s how you could use a JavaScript regular expression to validate an email address:

const emailRegex = /^(([^<>()\[\]\\.,;:\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 pass = ''

// true

const fail = 'fraser hamilton'

// false

If you want to be able to accept unicode you should use this regex instead:

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

const email = 'Dö'


// true

Written by Fraser Hamilton a full stack developer based out of Edinburgh, Scotland.

© 2020, Fraser Hamilton