views:

828

answers:

5

What are you using to validate users' email addresses, and why?

I had been using validates_email_veracity_of which actually queries the MX servers. But that is full of fail for various reasons, mostly related to network traffic and reliability.

I looked around and I couldn't find anything obvious that a lot of people are using to perform a sanity check on an email address. Is there a maintained, reasonably accurate plugin or gem for this?

P.S.: Please don't tell me to send an email with a link to see if the email works. I'm developing a "send to a friend" feature, so this isn't practical.

A: 

There are basically 3 most common options:

  1. Regexp (there is no works-for-all e-mail address regexp, so roll your own)
  2. MX query (that is what you use)
  3. Generating an activation token and mailing it (restful_authentication way)

If you don't want to use both validates_email_veracity_of and token generation, I'd go with old school regexp checking.

Yaroslav
+6  A: 

Don't make this harder than it needs to be. Your feature is non-critical; validation's just a basic sanity step to catch typos. I would do it with a simple regex, and not waste the CPU cycles on anything too complicated:

/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/

That was lifted from http://www.regular-expressions.info/email.html -- which you should read if you really want to know all the tradeoffs. If you want a more correct and much more complicated fully RFC822-compliant regex, that's on that page too. But the thing is this: you don't have to get it totally right.

If the address passes validation, you're going to send an email. If the email fails, you're going to get an error message. At which point you can tell the user "Sorry, your friend didn't receive that, would you like to try again?" or flag it for manual review, or just ignore it, or whatever.

These are the same options you'd have to deal with if the address did pass validation. Because even if your validation is perfect and you acquire absolute proof that the address exists, sending could still fail.

The cost of a false positive on validation is low. The benefit of better validation is also low. Validate generously, and worry about errors when they happen.

SFEley
+1  A: 

With rails 3.0 you can use a email validation without regexp

Here is my implementation : http://my.rails-royce.org/2010/07/21/email-validation-in-ruby-on-rails-without-regexp/

+1  A: 

Like SFEley said it depends on how thorough you want to be. In most cases, his regex is enough. I just use ruby's TMail library to validate any legal email address, perhaps at the expense of some CPU cycles.

begin
  TMail::Address.parse(email_address)
  return true
rescue
  return false
end
StefanO
+1  A: 

I created a gem for email validation in Rails 3. I'm kinda surprised that Rails doesn't include something like this by default.

http://github.com/balexand/email_validator

balexand