Ruby中的官方电子邮件验证

时间:2017-07-20 20:40:22

标签: ruby-on-rails ruby regex email-validation

我只希望官方电子邮件地址(例如xyz@company.com)注册我的服务而不是其他通用电子邮件地址,例如gmail.com或Yahoo mail.com

是否有红宝石来实现这种电子邮件验证?如果没有,如何实现这一目标?

2 个答案:

答案 0 :(得分:3)

您可以在相应的模型中编写自定义验证,如下所示:http://www.rails-dev.com/custom-validators-in-ruby-on-rails-4

本文的基本思路如下:

制作验证方法,并将其放入名为'验证器'

的新目录中
# app/validators/email_validator.rb
class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless value =~ /\A([^@\s]+)+@yourdomain.com\z/i
      record.errors[attribute] << (options[:message] || "wrong email address")
    end
  end
end

(我还没有测试过这个正则表达式!请使用类似http://rubular.com/的内容并插入您自己的电子邮件域模式以确保它正常工作。)

然后确保Rails知道加载新的验证器目录:

# config/application.rb
config.autoload_paths += %W["#{config.root}/app/validators/"]

然后将新验证(电子邮件)添加到适当的模型中:

#MyModel.rb    
validates :my_email_field, email: true

答案 1 :(得分:0)

有一个免费的MailboxValidator Web服务,您可以在Ruby中执行实时电子邮件地址验证。

https://github.com/MailboxValidator/mailboxvalidator-ruby

require "mailboxvalidator_ruby"

apikey = "MY_API_KEY"
email = "example@example.com"

mbv = MailboxValidator::MBV.new()
mbv.apikey = apikey
mbv.query_single(email)

if mbv.error != nil
    puts "Error: #{mbv.error}"
elsif mbv.result != nil
    puts "email_address: #{mbv.result.email_address}"
    puts "domain: #{mbv.result.domain}"
    puts "is_free: #{mbv.result.is_free}"
    puts "is_syntax: #{mbv.result.is_syntax}"
    puts "is_domain: #{mbv.result.is_domain}"
    puts "is_smtp: #{mbv.result.is_smtp}"
    puts "is_verified: #{mbv.result.is_verified}"
    puts "is_server_down: #{mbv.result.is_server_down}"
    puts "is_greylisted: #{mbv.result.is_greylisted}"
    puts "is_disposable: #{mbv.result.is_disposable}"
    puts "is_suppressed: #{mbv.result.is_suppressed}"
    puts "is_role: #{mbv.result.is_role}"
    puts "is_high_risk: #{mbv.result.is_high_risk}"
    puts "is_catchall: #{mbv.result.is_catchall}"
    puts "mailboxvalidator_score: #{mbv.result.mailboxvalidator_score}"
    puts "time_taken: #{mbv.result.time_taken}"
    puts "status: #{mbv.result.status}"
    puts "credits_available: #{mbv.result.credits_available}"
    puts "error_code: #{mbv.result.error_code}"
    puts "error_message: #{mbv.result.error_message}"
end