0

I have following regex:

var emailRegex = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"

And when I am trying to type:

asd@asd

It matches. Why?

Kaspar Lee
  • 5,446
  • 4
  • 31
  • 54
uksz
  • 18,239
  • 30
  • 94
  • 161
  • 1
    Because that is a valid email address. – JJJ Apr 21 '16 at 10:31
  • @Juhana, can you explain? – uksz Apr 21 '16 at 10:32
  • 1
    According to the specs, a TLD by itself is allowed in an address. In practice nobody has such a public address, but it's still valid. – JJJ Apr 21 '16 at 10:34
  • The problem is that the backslashes need to escaped as you're using the string to create regex. Either use regex literal or escape the backslashes. – Tushar Apr 21 '16 at 10:51

2 Answers2

2

Email services don't have to be connected to any domain. Following emails are all correct:

  • cezary@localhost
  • cezary@192.168.1.100
  • cezary@domain
  • cezary@com

See more under "Valid email addresses": https://en.wikipedia.org/wiki/Email_address

So if you want to allow only public emails, try other regexp :-)

Cezary Daniel Nowak
  • 1,096
  • 13
  • 21
-3

Validate email address in JavaScript? answer your question
Try this:

function validateEmail(email) {
    var re = /^(([^<>()\[\]\\.,;:\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,}))$/;
    return re.test(email);
}
alert(validateEmail("test@gmail.com"));
Community
  • 1
  • 1
Anh Nam
  • 1
  • 1