Hi,
OK, that particular regexp assumes you have a 2 or 3 character TLD on
the address:
irb(main):004:0> ‘[email protected]’ =~ /^\w+([.-]?\w+)@\w+
([.-]?\w+)(.\w{2,3})+$/
=> 0
Unfortunately, that doesn’t work for *.info and *.name email address,
like my own personal email address for example:
irb(main):003:0> '[email protected]' =~ /^\w+([\.-]?\w+)*@\w+
([.-]?\w+)*(.\w{2,3})+$/
=> nil
So, how would we construct an accurate, definitive check? Looking at
the EBNF in the relevant RFCs (2821 and 2822), I previously came up
with the following (it was written in Python; I’m converting to ruby
on the fly so it needs checking):
def validate_address(addr)
atext = ‘0-9a-zA-Z!#$%&'*+_/=?^-`{|}~’
subdomain = '[0-9a-zA-Z][0-9a-zA-Z-][0-9a-zA-Z]’
localpart, domain = addr.split ‘@’, 2
return false if domain.empty?
return false unless localpart =~ /^([#{atext}][.#{atext}]|“[^\”]
*")$/
return false unless domain =~ /^#{subdomain}(.#{subdomain})+/
return true
end
You could chuck that into the completely unreadable single regexp:
EMAIL_VALIDATION = /^([0-9a-zA-Z!#$%&'*+_/=?^-\{|\}~][.0-9a- zA-Z!#\$%\&\'\*\+_\/=\?^\-
{|}~]|“[^\”]")@[0-9a-zA-Z][0-9a-zA-Z-]
*0-9a-zA-Z+$/
Note that this is only checking the email address itself. Bear in
mind that if you’re dealing with email, rather than just getting an
address from a form, you have to deal with parsing out the address
from the ‘“Name” [email protected]’ string.
Cheers,
Graeme
On 10 May 2006, at 17:12, szymek wrote:
Here’s a good regexp tutorial: http://www.regular-expressions.info/
–
Posted via http://www.ruby-forum.com/.
Rails mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails
–
Graeme Mathieson, Technical Director, Rubaidh Ltd
[email protected] http://www.rubaidh.com/
Scottish for Ruby on Rails