This was originally built for Anonybuzz and is now used at StarTalent. This gem provides a robust mechanism to validate email addresses and restrict account creation to corporate email accounts.
This gem also ships with a data-set of free and disposable email domains which are used for validation checks.
You can also block certain usernames from creating accounts. Examples: admin, root
- Uses the mail gem.
- Checks the domain's MX record
- Validate against a blacklist of domains
- Validates against a list of free email providers
- Validates against a list of disposable email providers
- A whitelist can be used to override these checks
Add this line to your application's Gemfile:
gem "email_check"
To validate just the format of the email address
class User < ActiveRecord::Base
validates_email :email
end
To validate that the domain has a MX record:
validates_email :email, check_mx: true
To validate that the email is not from a disposable or free email provider:
validates_email :email, not_disposable:true, not_free:true
To validate that the domain is not blacklisted:
validates_email :email, not_blacklisted:true
To validate that the username is not blocked
validates_email :email, block_special_usernames:true
Everything together:
validates_email :email,
check_mx: true,
not_disposable:true,
not_free:true,
not_blacklisted:true,
block_special_usernames:true,
message: "Please register with your corporate email"
To turn everything on by default, you can use the validates_email_strictness helper.
# Example above
validates_email_strictness :email
# Everything but allow free emails. This is what most people would want to use
validates_email_strictness :email, not_free:false
The lists are exposed as assignable arrays so you can customize them or load whatever data you please.
Add a config/intializers/email_check.rb
# Set disposable email domains
EmailCheck.disposable_email_domains = ['freemail.org']
# Append to the whitelist
EmailCheck.whitelisted_domains << 'gmail.com'
EmailCheck.free_email_domains << 'thenewgmail.com'
# Setting a domain in the blacklist will also blacklist all subdomains
EmailCheck.blacklisted_domains << 'lvh.me'
# Block the 'anonymous' username for all domains
EmailCheck.blocked_usernames << 'anonymous'
This gem is tested with Rails 4.0+. Ruby versions tested:
- Ruby 2.3
- Ruby 2.5
Rails versions tested:
- Rails 4.0
- Rails 5.0
- Rails 6.0
- This code is heavily based upon: lisinge/valid_email2
- Data is from: lavab/disposable and willwhite/freemail
- Fork it ( https://github.com/dapatil/email_check/fork )
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request