I am following Ryan Bates' Railscast. I find when I tried to establish my customized field validator, my rails 3 is not working as expected.
I established a new email_format_validator.rb file in under lib/ and the codes are:
class EmailFormatValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
object.errors[att开发者_JAVA技巧ribute] << (options[:message] || "is not formatted properly")
end
end
end
I put this line in my user.rb (Model file):
validates :email, :presence => true, :uniqueness => true, :email_format=>true
The browser complained:
Unknown validator: 'email_format'
Why? How to solve this?
You will need to restart your server. The lib
directory isn't loaded by default, so you'll need to restart your Rails server in order to load this validator.
Edit:
Try putting them under lib/validators
and restarting the server...
I put 'email_format_validator.rb' under 'config/initializers'. And then restart the server. Everything is working now..
精彩评论