Wednesday, January 05, 2005

javascript regexp email validator

I have been looking for a javascript email regexp email validator. And I found one from this web site. And the code is "/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i"

This code looks nice.

However, I am not totally satisfied with the code. Because there are emails addresses don't look like "abc@abc.com". For example, I used to send email to an address like "joel@192.168.100.1". So I am going to make some change to the regular expression filter.

Update 1: "/^([\w-]+(?:\.[\w-]+)*)\@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$|(\[?(\d{1,3}\.){3}\d{1,3}\]?)$/i" will detect email like "abc@127.0.0.1" or "abc@[127.0.0.1]".

Update 2: /^([\w-]+(?:\.[\w-]+)*)\@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$|(\[?(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\]?)$/i

Now this one won't let a.b.c@256.0.0.0 slip.

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

Now this regular expression thinks "Guy Joel"@abc.com or "Guy Joel"guyj@abc.com are good email address.

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

A little bit more update on space in the regexp.

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

Made a big mistake in the last one. So, another update.

Update 6: /^(("[\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]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\]?)$/i

It's getting longer and longer, better and better.

Update 7: /^(("[\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

The update 6 thinks 256.255.255.255 is a legal ip address, fixed in update 7.

stringresult
joel@joel.compass
joel@joel.edupass
joel@joel.museumpass
joel@joel.ac.ukpass
joel@guy.joel.ac.ukpass
guy.joel@guy.joel.ac.ukpass
guy.joel@127.0.0.1pass
guy.joel@[127.0.0.1]pass
\"Guy Joel\"guy.joel@[127.0.0.1pass
\"Guy Joel\"@[127.0.0.1]pass
\"Guy Joel\"@9.999.99.25fail
\"Guy Joel\"@999.99.99.25fail
"\"Guy Joel\""fail

Also, regular expression for url validation.

Labels: , , ,