Email Validation with apostrophe

Hello all,

Whoever allowed apostrophes to be valid within emails needs some talking to!

Anyway. I have just found out that this JS function I have been using and have no idea how it works does not allow emails with apostrophes in it. Does anyone know how to alter this code to allow apostrophes?

var pattern = 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);

Apostrophes aren’t valid in emails afaik? Are you sure?

Also that’s an extremely complicated regex for a simple email address… :smiley:

Try

/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/

And if you want an apostrophe allowed,

/^([a-zA-Z0-9_.-'])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/

Here’s how it works

[list][]^ start of string
[
]( two types of names are acceptable

[list]*|([\w-]+(?:\.[\w-]+))
[
]|(“[\w-\s]+”)([\w-]+(?:\.[\w-]+))
[/list][
])
[*] two types of domains are acceptable

[list]*
[*]|(@\[? optional bracket around domain name

[list]*
*{2}
*
[/list][]\]?) optional bracket around domain name
[/list][
]$ end of string
[/list]

Thank you Mal and pmw57 for your quick reply and help!

Yes apostrophes are valid in emails - not to be funny but Ireland email addresses use apostrophes all the time - there are lots of o’ surnames.

Its mental I know to allow apostrophes in email - just look at some of the old code around interfacing with databases. I think alot of developers did not even think to counter for that type of email address.

I will try your regex out Mal!

Cheers

Marc

Hello Mal,

Sorry but I get a JS error come up in IE - here is my code - maybe I am not ending this working this correctly in the statement?

var pattern = new RegExp(/^([a-zA-Z0-9_.-'])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/i);

also tried

var pattern = new RegExp(/^([a-zA-Z0-9_.-'])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/);

The minus sign needs to be escaped, as in \-

Otherwise it will be seen as a continuation symbol, as in 0-9

Hello pmw57

So it should be…

var pattern = new RegExp(/^([a-zA-Z0-9_.\-'])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/);

Either that or move the - to be the last character in the group instead of the ’ being last

Thanks! It worked!