开发者

rails3 doesn't load my validators in lib

I put EmailValidator in lib/validators/email_validator and it's not workings (I put root/lib in the load_path)

here is the cod开发者_StackOverflowe.. I put the class in module validators as the parent folder name

class Validators::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

I get the error Unknown validator: 'email'


You have two options:

  1. Either put your custom validator under config/initializers.
  2. Or add lib/validators to the autoload path in config/application.rb.

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

Personally I would go with the second option as lib/validators makes for good encapsulation.


Since you put your custom validator in the Validators:: in the lib/validators, you have to reference it with that namespace also.

validates :email, presence: true, :'validators/email' => true


UPDATE: You need this:

module Validators
  class EmailValidator < ActiveModel::EachValidator
    def validate(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
end

class YourModel < ActiveRecord::Base
  include Validators

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

Otherwise, you need to put your validator class under the ActiveModel::Validations namespace. When you namespace a class, ActiveRecord isn't going to see it, if that namespace isn't a namespace it has already included.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜