Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 code.. 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'

like image 396
gilsilas Avatar asked May 19 '11 11:05

gilsilas


3 Answers

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.

like image 103
Douglas F Shearer Avatar answered Oct 18 '22 13:10

Douglas F Shearer


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
like image 43
lulalala Avatar answered Oct 18 '22 15:10

lulalala


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.

like image 43
d11wtq Avatar answered Oct 18 '22 14:10

d11wtq