Last active
August 3, 2016 09:20
-
-
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 :-)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/application.rb | |
[...] | |
config.autoload_paths += %W["#{config.root}/app/validators/"] | |
[...] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/locales/fr.yml | |
fr: | |
activerecord: | |
errors: | |
email_format: "doit être une adresse valide" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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