Skip to content

Instantly share code, notes, and snippets.

@tbuyle
Last active August 3, 2016 09:20
Show Gist options
  • Save tbuyle/f11dcf44e2e6695ecfacf4c5ce79e509 to your computer and use it in GitHub Desktop.
Save tbuyle/f11dcf44e2e6695ecfacf4c5ce79e509 to your computer and use it in GitHub Desktop.
Rails Custom Validator for email with I18n message. Regex is simple but should be enough. Add https://github.com/mailcheck/mailcheck for even less invalid emails :-)
# config/application.rb
[...]
config.autoload_paths += %W["#{config.root}/app/validators/"]
[...]
# app/validators/email_validator.rb
class EmailValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
record.errors.add(attribute, (options[:message] || :email_format))
end
end
end
# config/locales/fr.yml
fr:
activerecord:
errors:
email_format: "doit être une adresse valide"
# app/models/my_model.rb
[...]
validates :email_attribute, email: true
[...]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment