开发者

Writing custom validator in Rails 3

I'm trying to write a custom validator that will check for the number of words entered into a text field.

I was trying to follow the example in railscasts episode 211 - http://railscasts.com/episodes/211-validations-in-rails-3

So I made a file /lib/word_limit_validator.rb and copied in the same code from the tutorial. I know that this code doesn't count the number of words, I am just trying to use it because I know how it is supposed to behave.

class WordLimitValidator < 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

Here's the line I used in my valid开发者_运维知识库ation:

  validates :body, :presence => true,
                   :word_limit => true

When I tried to load the form I got the following error:

Unknown validator: 'word_limit'

How do I get rails to recognize my validator?

System spec: Mac OS 10.6.7 Rails 3.0.4 ruby 1.9.2p136


You could also create an app/validators directory in your rails project and put your custom validators there. This way they will automatically be loaded.


Files in lib/ aren't autoloaded anymore in Rails. So, you have a few options.

  • You can add lib to your autoload paths in your application.rb:
    config.autoload_paths += %W( #{config.root}/lib )
  • You can include by adding file with something like this to config/initializers: require File.join( Rails.root, 'lib', 'word_limit_validator')
  • If you only need it one place, you can just put it in the same file as your model.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜