ruby email address validation regex

Posted by on Jan 15th, 2007
2007
Jan 15

one of the things i end up having to do day in and day out is validating email addresses before shoving them into a database. honestly, i haven’t been doing it as well as i should be. the only real reason i haven’t is that i didn’t have time to sit around with the ruby book and plod through how they do regex. this weekend, i cracked the book and it was simple.

there are a bunch of decent canned javascripts to do just this, but in alot of cases, our email are sent via AJAX, so it would be really handy to do this with ruby and part of a rails controller.

before i got too involved in the whole thing (i did digest the chapter, though) i did a quick google on a regex. i am not at all opposed to borrowing other people’s code.

over at “devx.com”:http://www.devx.com/enterprise/Article/31197/0/page/3 i found this really keen regex:

/\A[\w._%-]+@[\w.-]+.[a-zA-Z]{2,4}\z/

here is my quick and dirty self explanatory test of how it works.

the code:

emails = ["test@example.com","jo@jo.com","rex","f4$m@you.com",
            "test@go,com","test@example.co", "test.example@example.c",
            "testing.example@example.com"]

emails.each do |e|
  if e =~ /\A[\w\._%-]+@[\w\.-]+\.[a-zA-Z]{2,4}\z/
    puts e + ” is a valid email address\n”
  else
    puts e + ” is not a valid address\n”
  end
end

as you would guess, produces output like this:

test@example.com is a valid email address
jo@jo.com is a valid email address
rex is not a valid address
f4$m@you.com is not a valid address
test@go,com is not a valid address
test@example.co is a valid email address
test.example@example.c is not a valid address
testing.example@example.com is a valid email address

let me know if you find anything that makes this regex choke..

One Response

  1. Mike Says:

    user+modifier@domain.com

    When email is sent to an address like this, it goes to the same mailbox as user@domain.com, but it allows people the flexibility to identify the site from which a recorded email address has disseminated.

    IE, here, I could post as
    mike+villagebuzz@mysite.com, and if you were to sell email addresses, I’ll know that it was you who is responsible for my email address being given to spammers. At that point, it’d be trivial to ignore any resulting spam with a simple filter rule.

Leave a Comment




XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.