Reputation: 7911
I am using a RegExp
for validating single email address. It validates ,
(comma) which it shouldn't.
Following is my regex:
^[-a-zA-Z0-9~!$%^&*_=+}{\'?]+(\.[-a-zA-Z0-9~!$%^&*_=+}{\'?]+)*@([a-zA-Z0-9_][-a-zA-Z0-9_]*(\.[-a-zA-Z0-9_]+)*\.([a-zA-Z]{2,})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$
It also works as expected on regex101.
Expected Output:
[email protected]
(valid)[email protected],test
(invalid)Is my regex wrong or there is some other issue?
Here's my snippet:
var regex = new RegExp("^[-a-zA-Z0-9~!$%^&*_=+}{\'?]+(\.[-a-zA-Z0-9~!$%^&*_=+}{\'?]+)*@([a-zA-Z0-9_][-a-zA-Z0-9_]*(\.[-a-zA-Z0-9_]+)*\.([a-zA-Z]{2,})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$");
console.log(regex.test("[email protected]"))
console.log(regex.test("[email protected],test"))
Upvotes: 1
Views: 103
Reputation: 19070
Here is an example with the regex used in type="email"
from W3C and here a link to Email Address Regular Expression That 99.99% Works.
Code example:
var regex = /^(([^<>()\[\]\\.,;:\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,}))$/;
console.log(regex.test('[email protected]'));
console.log(regex.test('[email protected],test'));
Upvotes: 1
Reputation: 7350
I think you're not escaping your regex. Just replace \
with \\
:
var regex = new RegExp("^[-a-zA-Z0-9~!$%^&*_=+}{\\'?]+(\\.[-a-zA-Z0-9~!$%^&*_=+}{\\'?]+)*@([a-zA-Z0-9_][-a-zA-Z0-9_]*(\\.[-a-zA-Z0-9_]+)*\\.([a-zA-Z]{2,})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,5})?$");
console.log(regex.test("[email protected]"))
console.log(regex.test("[email protected],test"))
\.
becomes just .
, inside the resulting in memory string. And that means any char is matched, instead of only a true dot. So need to escape twice, one for the string encoding, and one for the regex escaping sequence.
In Regex101 you write the Regex, not a JavaScript representation of the Regex. So you don't need the escaping required by JavaScript.
Upvotes: 3