Take me home

Monolithic e-mail validators sucks

Published January 17, 2010

validates_format_of :email,
  :with => /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/
  :message => "E-mail is invalid"

Great error messages are cornerstones in great applications.

“E-mail is invalid” is not a great error message.

Invalid? What’s invalid about it? What can you do to make it valid?

I think you should be nicer to your users. Stop worrying about compliance with the RFCs, and validate erroneous user input instead.

validates_format_of :email,
  :with => /@/,
  :message => "Needs to contain an @."

validates_format_of :email,
  :with => /\.[^\.]+$/,
  :message => "Has to end with .com, .org, .net, etc."

validates_format_of :email,
  :with => /^.+@/,
  :message => "Must have an address before the @"

validates_format_of :email,
  :with => /^[^@]+@[^@]+$/,
  :message => "Must be of the format 'something@something.xxx'"

Now we’re talking. By having many small validators instead of one large, you get to pick an error message for each validator. Much better than a global and generic “not valid”. Your user gets to know what went wrong, and what he or she can do to fix it.

And you won’t need a black belt in regular expressions, either.

Questions or comments?

Feel free to contact me on Twitter, @augustl, or e-mail me at august@augustl.com.