Skip to content

Instantly share code, notes, and snippets.

@tongrhj
Last active December 22, 2016 07:05
Show Gist options
  • Save tongrhj/07ff8ae75219c6ad57c6c7fc4d0a50f7 to your computer and use it in GitHub Desktop.
Save tongrhj/07ff8ae75219c6ad57c6c7fc4d0a50f7 to your computer and use it in GitHub Desktop.
Email Validator Regex
function isEmail (str) {
return str ? /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/.test(str) : false
}
const test = require('ava')
const sinon = require('sinon')
test('validate#isEmail returns true if unicode emails', t => {
t.true(isEmail('💩+तфâ.πüñó1@ӕ.昭字'))
})
test('validate#isEmail returns true no matter the length of the email', t => {
t.true(isEmail('the-total-length@of-an-entire-address.cannot-be-longer-than-two-hundred-and-fifty-four-characters.and-this-address-is-255-characters-exactly.so-it-should-be-invalid.and-im-going-to-add-some-more-words-here.to-increase-the-length-blah-blah-blah-blah-bl.org'))
})
test('validate#isEmail returns false if email is blank', t => {
t.false(isEmail(''))
t.false(isEmail(' '))
})
test('validate#isEmail returns false if no . in TLD', t => {
t.false(isEmail('foo@bar'))
t.false(isEmail('f.oo@bar'))
})
test('validate#isEmail returns false if less or more than one @', t => {
t.false(isEmail('invalid'))
t.false(isEmail('invalid@[email protected]'))
})
test('validate#isEmail returns false only for certain special characters', t => {
t.false(isEmail('<>()[],;:"@email.com'))
t.true(isEmail("!#!$%&'*+-./\=?^_`{}|[email protected]"))
t.false(isEmail('[email protected]'))
t.false(isEmail("partially.\"quoted\"@sld.com"))
t.false(isEmail('a b [email protected]'))
})
test('validate#isEmail returns false if TLDs shorter than 2 characters', t => {
t.false(isEmail('[email protected]'))
t.false(isEmail('[email protected].'))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment