justin․searls․co

Validating email addresses in Rails

Nice set of reminders on how to validate e-mail addresses in Rails models and was glad to find his second example to be almost identical to what I found in my newest app:

class User < ApplicationRecord
  validates :email,
    format: { with: URI::MailTo::EMAIL_REGEXP },
    presence: true,
    uniqueness: { case_insensitive: true }
end

One thing I'd be sure to add, though, is the new normalizes class method to ensure all email addresses saved by your app are easily compared by stripping whitespace and lower-casing them. From my User class:

normalizes :email, with: ->(email) { email.strip.downcase }

Never hurts to revisit the stuff you wrote on the first day of an app's life.


Got a taste for fresh, hot takes?

Then you're in luck, because you can subscribe to this site via RSS or Mastodon! And if that ain't enough, then sign up for my newsletter and I'll send you a usually-pretty-good essay once a month. I also have a solo podcast, because of course I do.