Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3, Unknown validator: 'EmailValidator'

I try to add an email-validator in my rails app. I created the following file /lib/validators/email_validator.rb

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

In the application.rb I added this line:

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

And here is my User model:

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

If i want to start the server I got an error:

Unknown validator: 'EmailValidator' (ArgumentError)

Has anybody an idea how I can fix this problem?

like image 746
Marvin Avatar asked Mar 07 '13 22:03

Marvin


2 Answers

If you place your custom validators in app/validators they will be automatically loaded without needing to alter your config/application.rb file.

Resource: Where should Rails 3 custom validators be stored? (second answer)

like image 114
Zippie Avatar answered Oct 03 '22 00:10

Zippie


This error occures, because rails loads model file before your validation file

Try to require your validation file manually at the start of your model file

require_dependency 'validators/email_validator.rb'
like image 30
edikgat Avatar answered Oct 03 '22 01:10

edikgat