Canna
Canna

Reputation: 3804

javascript email validation check condition issue

example,

<input id="email" name="email" style="width:100%;" type="text">

javascript,

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);
} 

this works fine in most cases,

but if the input is

2★@2.com

something like this kind of input with special char

it doesn't validate it.

any good solution?

Upvotes: 0

Views: 990

Answers (2)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382464

Read Stop Validating Email Addresses With Complicated Regular Expressions.

As it says, this email :

"Look at all these spaces!"@example.com

is perfectly valid.

Conclusion :

  1. Don't use a complex regex to validate email. /@/ is fine to check most user errors
  2. Validate by sending an email and waiting for answer

Seriously, any attempt at solving the problem with a complex regex is doomed and usually keeps being worse with fixes

Upvotes: 1

Rob
Rob

Reputation: 3574

Validating client-side is pretty pointless, as users can remove or even edit it. You have to check it serverside too, or don't validate at all and just mail!

 var emailfilter = /(([a-zA-Z0-9\-?\.?]+)@(([a-zA-Z0-9\-_]+\.)+)([a-z]{2,3}))+$/;
  if(emailfilter .test(string)) { //mail

}

There is no way you can validate if an emailaddress exists without mailing and waiting for the user to click the confirmation url. You only can validate if they match patterns which an email should look like.

Upvotes: 0

Related Questions