Rails 3: Custom error message in validation
I don't understand why the following is not working in Rails 3. I'm getting "undefined local variable or method `custom_message'" error.
validates :to_email, :email_format => { :message => custo开发者_如何转开发m_message }
def custom_message
self.to_name + "'s email is not valid"
end
I also tried using :message => :custom_message instead as was suggested in rails-validation-message-error post with no luck.
:email_format is a custom validator located in lib folder:
class EmailFormatValidator < 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 valid')
end
end
end
Just for reference, this is what I believe is going on. The 'validates' method is a class method, i.e. MyModel.validates(). When you pass those params to 'validates' and you call 'custom_message', you're actually calling MyModel.custom_message. So you would need something like
def self.custom_message
" is not a valid email address."
end
validates :to_email, :email_format => { :message => custom_message }
with self.custom_message defined before the call to validates.
If anyone is interested I came up with the following solution to my problem:
Model:
validates :to_email, :email_format => { :name_attr => :to_name, :message => "'s email is not valid" }
lib/email_format_validator.rb:
class EmailFormatValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
error_message = if options[:message] && options[:name_attr]
object.send(options[:name_attr]).capitalize + options[:message]
elsif options[:message]
options[:message]
else
'is not valid'
end
object.errors[attribute] << error_message
end
end
end
Maybe the method "custom_message" needs to be defined above the validation.
精彩评论