Vin*_*ent 5 forms validation activemodel ruby-on-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
Run Code Online (Sandbox Code Playgroud)
我也尝试使用: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
Run Code Online (Sandbox Code Playgroud)
如果有人感兴趣,我想出了以下解决方案来解决我的问题:
模型:
validates :to_email, :email_format => { :name_attr => :to_name, :message => "'s email is not valid" }
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4435 次 |
| 最近记录: |