Reputation: 3717
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 validation:
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
Upvotes: 2
Views: 3505
Reputation: 14817
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.
Upvotes: 10
Reputation: 6736
Files in lib/ aren't autoloaded anymore in Rails. So, you have a few options.
config.autoload_paths += %W( #{config.root}/lib )
require File.join( Rails.root, 'lib', 'word_limit_validator')
Upvotes: 1