Last Updated: February 25, 2016
·
334
· frunns

I18n translations in validation

Recently had to edit some code where the email validation message was hardcoded and used different wording from other places on the site, where I18n is used. Turns out it was about as simple as I've come to expect.

class EmailValidator < ActiveModel::EachValidator
  def validate_each(object, attribute, value)
    unless valid?(value)
      # From this:
      # object.errors[attribute] << (options[:message] || "is an incorrect email")
      # to this:
      object.errors.add(attribute, (options[:message] || :invalid))
    end
  end

  def valid?(str)
    EmailValidator.valid?(str)
  end

  def self.valid? str
    return unless str.present?
    !!str.match(/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i)
  end
end