Peter Gibbons
Peter Gibbons

Reputation: 103

Edit regular expression to support + (plus) notation

I'm using a regex to 'quick and dirty' validate an email address client side and I just found out it doesn't support the + plus notation ([email protected]) google provides its users. I'm sure it fails in other points as well. How can I edit this to support + notation and ensure I'm dealing with an email address while not pissing anyone with an oddly formed email address off?

`var emailReg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]`{2}|[0-9]{1,2})\]?$)/i);

Word wrapped:

var emailReg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);

Thank you,

Upvotes: 0

Views: 75

Answers (2)

borgille
borgille

Reputation: 33

You could use this:

^(("[\w-\s]+")|([\w-]+(?:[.+][\w-]+)*)|("[\w-\s]+")([\w-]+(?:[.+][\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)

It's still quick and dirty. It will allow your example [email protected], but will also allow [email protected]. It won't allow for [email protected] or [email protected].

Upvotes: 1

Garis M Suero
Garis M Suero

Reputation: 8170

I just copied your regular expression and removed an extra parenthesis and is working fine to me:

^(("[\w-\s]+")|([\w-]+(?:.[\w-]+))|("[\w-\s]+")([\w-]+(?:.[\w-]+)))(@((?:[\w-]+.)*\w[\w-]{0,66}).([a-z]{2,6}(?:.[a-z]{2})?)$)|(@[?((25[0-5].|2[0-4][0-9].|1[0-9]{2}.|[0-9]{1,2}.)((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2}).){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})]?$

Live demo:

https://regex101.com/r/kX3jW0/1

Upvotes: 0

Related Questions