datatype_void datatype_void - 6 months ago 55
Javascript Question

Converting C# Regular Expression to Javascript Compatible Variant

I am currently building some custom form validators and using regular expressions to test the validity of email address against. I got the

regex
^(?(")(".+?(?<!\\)"@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$
from MSDN | How to: Verify that Strings Are in Valid Email Format and attempted to convert it using RegexBuddy, but I get the following error:

RegexBuddy Error

I am not exactly a
regex
wizard but some help would be greatly appreciated. I think that alternation could be used for the conditional, but I am greatly unsure of the
lookbehind
construct.

Edit: If you read the comments on that SO post you'll see that none of those are perfect, and this approach is documented by Microsoft, so it's a little more tested than many of those.

Answer

JavaScript does not support look-behinds or conditionals.

This is the regex that I use for email validation in my custom forms. It works great in JavaScript.

/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$/g

https://regex101.com/r/bB9vK2/3

And a version that supports non ASCII characters, though be careful as some programs may have trouble processing non ASCII characters.

^([a-zA-Z0-9._%+-]|[^\x00-\x7F])+?@([a-zA-Z0-9.-]|[^\x00-\x7F])+\.([a-zA-Z]|[^\x00-\x7F]){2,63}$

https://regex101.com/r/bB9vK2/4

As always, remember that client-side validation is no replacement for server-side validation and is mainly to improve user experience.

Here is a very detailed explanation about how to choose an email regex including a reference to the practical limitations of TLD length based on the capability of SMTP (Max 63 characters) and explanation of the official standard RFC 5321

http://www.regular-expressions.info/email.html

You can find out about lookbehinds and conditionals on this site: http://www.regular-expressions.info/lookaround.html

Experiment with regular expressions here: https://regex101.com/