自定义验证栏

时间:2013-12-23 07:01:24

标签: ruby-on-rails ruby validation ruby-on-rails-3.2

我在模块中有EmailValidator类,如:

module ActiveModel
  module Validations
    class EmailValidator < EachValidator
      def validate_each(record, attribute, value)
        if value.presence && (value =~ /\A[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]+\z/).nil?
          record.errors[attribute] << (options[:message] || "is invalid")
        end
      rescue => e
        record.errors[attribute] << (options[:message] || "is invalid")
      end
    end
  end
end

我试图在我的模型中使用它,但是当我尝试启动rails server =&gt;时面临加载错误 email_validator.rb 定义EmailValidator LoadError

任何人都可以帮我吗?

3 个答案:

答案 0 :(得分:0)

我建议改用the valid_email gem,因为验证电子邮件地址确实很痛苦!

class User < ActiveRecord::Base
  validates :email, :presence => true, :email => true

  # ...
end

另请参阅根据RFC 822实际验证电子邮件地址的this humongous regular expression

答案 1 :(得分:0)

validates_format_of:email,:with =&gt;〜/\A[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+。[A-Za Z] + \ Z /

答案 2 :(得分:0)

您可以尝试使用这种语法并根据此 blog实现您应该非常有用的代码: -

class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    if value.presence && (value =~ /\A[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]+\z/).nil?
      record.errors[attribute] << (options[:message] || "is invalid")
    end
  rescue => e
    record.errors[attribute] << (options[:message] || "is invalid")
  end
end

将此文件放入app / validators / email_validator.rb

for rails 3自定义验证请read此博客。

在Rails 4中

class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
    record.errors[attribute] << (options[:message] || "is not an email")
  end
 end
end

class foo < ActiveRecord::Base
  validates :email, presence: true, email: true
end

最后非常简单和干燥使用reg。 EXP: -

/\A[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]+\z/

改编自http://www.regular-expressions.info/email.html