【问题标题】:What is the best/easy way to validate an email address in Ruby?在 Ruby 中验证电子邮件地址的最佳/简单方法是什么?
【发布时间】:2011-06-14 04:43:54
【问题描述】:

在 ruby​​ 中(在服务器端)验证电子邮件地址的最佳/简单方法是什么?

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-3


【解决方案1】:

您可以查看它是否与此 Rails 验证器中使用的正则表达式匹配:

validates_format_of :email,:with => /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/

但如果您使用 Devise,只需执行以下操作:

validates_format_of :email,:with => Devise::email_regexp

来源:http://lindsaar.net/2008/4/14/tip-4-detecting-a-valid-email-address

编辑 1:

有用的测试网站:http://www.rubular.com/

【讨论】:

  • 这会验证“test.com”吗?对我来说失败了。
  • 不,它不是电子邮件
  • 我的意思是它把它当作一封电子邮件。
  • @ArtemKalinchuk 感谢您的评论!我已经更新了,实际上我现在依靠 Devise regexp 来重复 DRY
  • 虽然我认为答案很好,但我不得不提一下 ruby​​ != rails.答案没有提供 ActiveRecord 验证范围之外的解决方案。
【解决方案2】:

在 Ruby 中?与任何语言中的方式相同。

向该地址发送一封确认电子邮件,其中包含一个链接,收件人必须单击该链接才能将电子邮件地址视为完全验证。

完美格式化地址可能仍然无效的原因有很多(该地址没有实际用户,被垃圾邮件过滤器阻止等等)。确定的唯一方法是成功完成某种描述的端到端事务。

【讨论】:

  • +1。正则表达式是一种很好的“琐碎拒绝”技术,但不是完整的解决方案。与正则表达式一起发送验证电子邮件似乎是相对最佳的。
  • 这是最好的建议。使输入 type=email 以触发基本标志。除此之外,只需发送一封确认电子邮件。
【解决方案3】:

发送一封确认邮件,我通常会使用这个验证器... D.R.Y.

# lib/email_validator.rb
class EmailValidator < ActiveModel::EachValidator

  EmailAddress = begin
    qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]'
    dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]'
    atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-' +
      '\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+'
    quoted_pair = '\\x5c[\\x00-\\x7f]'
    domain_literal = "\\x5b(?:#{dtext}|#{quoted_pair})*\\x5d"
    quoted_string = "\\x22(?:#{qtext}|#{quoted_pair})*\\x22"
    domain_ref = atom
    sub_domain = "(?:#{domain_ref}|#{domain_literal})"
    word = "(?:#{atom}|#{quoted_string})"
    domain = "#{sub_domain}(?:\\x2e#{sub_domain})*"
    local_part = "#{word}(?:\\x2e#{word})*"
    addr_spec = "#{local_part}\\x40#{domain}"
    pattern = /\A#{addr_spec}\z/
  end

  def validate_each(record, attribute, value)
    unless value =~ EmailAddress
      record.errors[attribute] << (options[:message] || "is not valid") 
    end
  end

end

在你的模型中

validates :email , :email => true

 validates :email, :presence => true, 
                :length => {:minimum => 3, :maximum => 254},
                :uniqueness => true,
                :email => true

【讨论】:

  • 可能没那么容易,但你必须写一次,每次需要时使用
  • 您是从@apneadiving 的网络链接中复制的吗?
【解决方案4】:

快捷方式:

 validates :email, :format => /@/

正规形式(正则表达式):

validates :email, :format => { :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/ }

来源:Validator Class

【讨论】:

    【解决方案5】:

    由于主要答案的博客站点已关闭,这是来自该站点的代码的 sn-p,通过 nice cachergist

    # http://my.rails-royce.org/2010/07/21/email-validation-in-ruby-on-rails-without-regexp/
    class EmailValidator < ActiveModel::EachValidator
      # Domain must be present and have two or more parts.
      def validate_each(record, attribute, value)
        address = Mail::Address.new value
        record.errors[attribute] << (options[:message] || 'is invalid') unless (address.address == value && address.domain && address.__send__(:tree).domain.dot_atom_text.elements.size > 1 rescue false)
      end
    end
    

    【讨论】:

      【解决方案6】:

      你可以使用

      <%=email_field_tag 'to[]','' ,:placeholder=>"Type an email address",:pattern=>"^([\w+-.%]+@[\w-.]+\.[A-Za-z]{2,4},*[\W]*)+$",:multiple => true%>
      

      【讨论】:

      • 您不想在控制器或模型中验证这一点。如果 html 做到了,你可以发送一个 http 命令并绕过这个检查。
      【解决方案7】:

      我知道这是一个老问题,但我一直在寻找一种简单的方法来做到这一点。我遇到了email_validator gem,它的设置和使用非常简单。

      作为验证者

      validates :my_email_attribute, :email =&gt; true

      模型外验证

      EmailValidator.valid?('narf@example.com') # boolean

      希望对大家有所帮助。

      快乐编码

      【讨论】:

        【解决方案8】:
        validates :email, presence: true, format: /\w+@\w+\.{1}[a-zA-Z]{2,}/
        

        检查电子邮件字段不为空,并且一个或多个字符都在“@”之前和之后

        添加了特殊性,@ 之前的任何 1 个或多个单词字符以及具体 1 . 之后和之间的任何 1 个或多个单词字符以及之后至少 2 个字母

        【讨论】:

        • 这会导致(有效)电子邮件失败,例如 rob@hs-soft.com
        • 是的,这太严格了,我会选择:.+@.+\.{1}.{2,}
        【解决方案9】:

        可以参考https://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_format_of

        validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i

        【讨论】:

          【解决方案10】:

          如果您使用的是 Rails/Devise - 除了 @apneadiving 的答案 -

          validates_format_of :email,:with => Devise::email_regexp
          

          Devise::email_regexp 取自 config/initializers/devise.rb

          config.email_regexp = /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-02-14
            • 2019-02-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多