Rails 3:验证中的自定义错误消息
我不明白为什么以下内容在 Rails 3 中不起作用。我收到“未定义的局部变量或方法‘custom_message’”错误。
validates :to_email, :email_format => { :message => custom_message }
def custom_message
self.to_name + "'s email is not valid"
end
我也尝试过使用 :message => :custom_message 相反,按照 rails-validation-message-error 帖子中的建议,但没有运气。
:email_format 是位于 lib 文件夹中的自定义验证器:
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
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 => custom_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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
仅供参考,我认为这就是正在发生的事情。 “validates”方法是一个类方法,即 MyModel.validates()。当您将这些参数传递给“validates”并调用“custom_message”时,您实际上是在调用 MyModel.custom_message。因此,您需要
在调用验证之前定义类似于 self.custom_message 的内容。
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
with self.custom_message defined before the call to validates.
如果有人感兴趣,我想出了以下解决方案来解决我的问题:
模型:
lib/email_format_validator.rb:
If anyone is interested I came up with the following solution to my problem:
Model:
lib/email_format_validator.rb:
也许需要在验证之上定义方法“custom_message”。
Maybe the method "custom_message" needs to be defined above the validation.