2013-03-07 22 views
16

我嘗試在我的Rails應用程序中添加一個電子郵件驗證器。我創建以下文件/lib/validators/email_validator.rbRails 3,未知驗證器:'EmailValidator'

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

在application.rb中添加此行:

config.autoload_paths << "#{config.root}/lib/validators"

這裏是我的用戶模型:

class User < ActiveRecord::Base 
    attr_accessible :email, :password,:name 
    validates :email, :presence => true, :uniqueness => true, :email => true 
end 

,如果我想啓動服務器我得到一個錯誤:

Unknown validator: 'EmailValidator' (ArgumentError) 

有沒有人有一個想法,我可以如何解決這個問題?

回答

-2

嘗試修改後的用戶模型;

class User < ActiveRecord::Base 

    attr_accessible :email, :password,:name 

    validates :email, :presence => true, :uniqueness => true 

end 
+0

這不是問題的解決 – edikgat 2014-06-20 10:54:00

4

此錯誤occures,becouse軌道載荷模型文件的驗證文件之前

嘗試手動要求您的驗證文件在你的模型文件的開始

require_dependency 'validators/email_validator.rb' 
+0

這對我有效... – Daryn 2015-09-05 17:39:50