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.