2008-04-13 17:27:28 +0000

Did you know that Rails has inbuilt a strong email handling library called (ahem) TMail? I just so happen to maintain this now (Minero Aoki wrote it), but it gives you a great way to validate email addresses…

Update

Rails 3.0 uses Mail now instead of TMail, here is another simple way to validate an email.

Original Post:

If you have ever tried to handle the validation of email addresses in your Rails app, you have probably ended up trying to use something like this to validate the address:

Which is getting better. But the problem with that now is that you need to maintain that email address regular expression… which is quite… umm… “complex” I think is a good word :)

Enter TMail!

TMail has an “Address” class. It will throw an invalid address exception if given an address it can’t handle (and it has about 2,000 test cases of email addresses it can handle, so you are pretty safe.)

Plus, as the maintainer, whenever I find a valid email that TMail can not handle, I fix it, and then you benefit at the next gem install tmail… so it all turns out good :)

To use it, dump this in your user model somewhere (assuming your user model has the attribute ‘email_address’)

def valid_email?
TMail::Address.parse(email)
rescue
errors.add_to_base(“Must be a valid email”)
end

lindsaar.net is proudly bought to you by the letters l, i, n, d, s, a, r, e and t.
The comments on this site belong to Mikel Lindsaar and do not reflect the viewpoint of my employer, parents or anyone else.
Powered by Sinatra