【问题标题】:Rails, validates email exclusionRails,验证电子邮件排除
【发布时间】:2013-08-24 21:11:53
【问题描述】:

我目前正在尝试用一些东西来验证电子邮件属性:

  1. 它的存在
  2. 使用正则表达式的格式
  3. 它的独特性
  4. 它不在邮件提供商列表中

卡在第四步了,不知道怎么实现,这一步主要是排除throwable mail provider。

我目前有这个:

  validates :email, :presence   => true,
                    :format     => { :with => email_regex },
                    :uniqueness => { :case_sensitive => false },
                    :exclude => Not working when I put a regex here

我的问题不是正则表达式,而是如何排除与排除正则表达式匹配的电子邮件。

你能帮我做吗?

此致,罗伯。

【问题讨论】:

  • 没有什么能比得上排除。您必须在 email_regex 或自定义验证中进行。
  • 如何进行自定义验证?

标签: ruby-on-rails validation email blacklist


【解决方案1】:

如果您使用 devise 进行用户身份验证,您可以在 devise.rb 中取消注释代码

  # Email regex used to validate email formats. It simply asserts that
  # one (and only one) @ exists in the given string. This is mainly
  # to give user feedback and not to assert the e-mail validity.
  # config.email_regexp = /\A[^@]+@[^@]+\z/

否则我认为你可以这样写

在模型中

  validates :email, uniqueness: true
  validate  :email_regex

 def email_regex
    if email.present? and not email.match(/\A[^@]+@[^@]+\z/)
      errors.add :email, "This is not a valid email format"
    end
  end

【讨论】:

    【解决方案2】:

    Rails 提供 exclusion 帮助器,而不是 exclude;无论如何,它验证属性的值不包含在给定的集合中。 (http://guides.rubyonrails.org/active_record_validations.html#exclusion)

    我认为您应该使用自定义验证方法来解决您的问题 (http://guides.rubyonrails.org/active_record_validations.html#custom-methods)。

    【讨论】:

      【解决方案3】:

      在你的模型中做这样的事情。

      validate :exclude_emails
      
      private
      
      def exclude_emails
      if ( self.email =~ /blah(.*)/ )
        errors.add_to_base("Email not valid")
      end
      end
      

      【讨论】:

      • add_to_base 已弃用。
      【解决方案4】:

      格式验证器有一个无选项(至少在 rails 4 和 3.2 中),所以...

      validates :email, :presence   => true,
                        :format     => { :with => email_regex},
                        :uniqueness => { :case_sensitive => false }
      validates :email, :format     => {:without => some_regex}
      

      【讨论】:

      • 感谢您的想法,但实际上我们不能同时放置 :with 和 :without 。但你知道我想要什么
      • 嗯,我不知道。没问题,你可以调用两次。更新了我的答案。
      猜你喜欢
      • 2023-03-29
      • 2011-01-26
      • 2019-02-21
      • 2011-06-28
      • 2013-09-29
      • 1970-01-01
      • 1970-01-01
      • 2019-03-09
      • 1970-01-01
      相关资源
      最近更新 更多