我想添加'请注意,您必须再次选择所有图像和相关车辆。'在任何验证错误结束时,无论有多少错误,例如将此文本添加到每个错误消息的末尾都不是一个选项,因为如果有多个错误消息,它将被多次显示错误。
有没有办法在验证错误消息的末尾添加特定文本?
尝试谷歌但没有找到任何东西。
答案 0 :(得分:1)
这很容易实现,但根据您列出的验证数量可能会很繁琐。我将举一些例子,以便您决定最符合您需求的套件:
如果使用Rails的内置验证(例如预设,唯一性等),您可以在验证中添加自己的消息以及标准输出,或者将其完全替换为您自己的消息:
validates :username, :email, :title, :another_attribute,:omg_another_attribute, :password, presence: { :message => "cant be blank. Notice that you have to select all the images and related vehicles again for not filling out the form ya dumbo!"}
这将列出他们留空的每个字段的错误消息。如果您想在所有错误消息的末尾添加一次错误以提醒他们这个问题,您可以进行自定义验证,检查其他错误,然后在最后添加一次,如:
#Make sure to put this custom validate method after all the other validators since they are run in order from top to bottom and you want to see if the others have failed
validate :add_blanket_error_when_one_or_more_errors_happen
def add_blanket_error_when_one_or_more_errors_happen
if self.errors.count > 0 then self.errors.add(:base, "Notice you were being dumb again and now have to fill more stuff out.") end
end
我通常会将这样的常规错误添加到“base”字段,但如果您不想添加额外的样式/标记,则可以将其附加到表单中的任何字段。在您看来,如果您选择将其添加到“基本”字段,则可以通过执行以下操作将此消息放在表单顶部(
) <% unless @the_form_object_youre_using_here.errors[:base].blank? %>
<div>
<span class="error-explanation"><%= @again_the_form_object_here.errors[:base].first %></span>
</div>
<% end %>
这也可以让你设定范围等。
不幸的是,您可以添加到模型中,以便为所有失败的验证附加一条消息。即使尝试看似无害的东西就像完成它一样的自定义验证(不要尝试,除非你有任务管理器准备好因为它会导致内存泄漏甚至会导致你的计算机崩溃,如果你不杀死进程快)
**DONT DO IT IF YOU ENJOY COORS LIGHT OR PREFER LONG WALKS ON THE BEACH**
validate :append_messages_to_all_failed_validations
def append_messages_to_all_failed_validations
self.errors.each do |attribute, error|
#**YOU SHOULDNT BE DOING THIS LOL**
self.errors[attribute.to_sym] = "#{error} plus some"
end
end