0

我正在使用 Rails 客户端验证 gem,版本 3.2.1。现在,我遇到了一个问题,现在在我不希望应用这些验证的表单上应用验证。

请找出我的两个表格,用于注册和登录。

_sign_up_form.html.erb
<%= form_for(@user, :validate => true, :remote => true) do |f| %>

_sign_in_form.html.erb
<%= form_for(@user_session, :remote => true) do |f| %

如您所见,我仅在我的注册表单上设置了 validate => true。

我希望这些客户端验证在 sign_up 表单上而不是在 sign_in 表单上工作。请注意,这两种形式都是在对各自控制器的“新”操作发出 ajax 请求之后加载的。

_sign_up_form.html.erb 在 users/new.js.erb 被渲染时被加载

*users/new/js.erb*
$("#static-form-modal .modal-body").html('<%= j(render(:partial => "users/sign_up_form"))%>');
$('form').live("click",function() {
$(this).enableClientSideValidations();
});

_sign_in_form.html.erb 在 user_sessions/new.js.erb 被渲染时被加载

*user_sessions/new.js.erb*
$('#static-form-modal .modal-body').html('<%= j(render(:partial => "user_sessions/sign_in_form"))%>');

客户端验证在注册表单中运行良好,错误消息显示在错误字段旁边。

问题是当我单击登录表单的提交按钮时,这些验证错误消息出现在错误字段旁边。显然,服务器端验证,但我无法想办法删除出现在错误字段旁边的那些错误消息。

另外,我不是简单的形式。我在 initializers/client_side_validations.rb 中取消了这些行的注释。

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
  unless html_tag =~ /^<label/
    %{<div class="field_with_errors">#{html_tag}<label for="#{instance.send(:tag_id)}" class="message">#{instance.error_message.first}</label></div>}.html_safe
  else
    %{<div class="field_with_errors">#{html_tag}</div>}.html_safe
  end
end

任何帮助将不胜感激。

4

2 回答 2

0

我不确定这是否是正确的方法,但我检查了实例是否响应 object_name 方法并相应地更改了我的代码。

请找到编辑后的代码。

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
  if html_tag =~ /^<label/ or instance.respond_to?(:object_name)
    %{<div class="field_with_errors">#{html_tag}</div>}.html_safe
  else
    %{<div class="field_with_errors">#{html_tag}<label for="#{instance.send(:tag_id)}" class="message">#{instance.error_message.first}</label></div>}.html_safe
  end
end

之前生成的代码可以在问题帖子中看到。

于 2012-11-26T07:58:10.637 回答
0

只是为了扩展 Sunil 已经正确的内容,如果您使用的是 Rubocop,它可能会抱怨使用html_safe并建议使用辅助方法。

这是 Sunil 更改代码的方法

ActionView::Base.field_error_proc = proc do |html_tag, instance|
    if html_tag =~ /^<label/
        ApplicationController.helpers.raw("<div class='field_with_errors'>#{html_tag}</div>")
    else
        ApplicationController.helpers.raw("<div class='field_with_errors'>#{html_tag}<label for='#{instance.send(:tag_id)}' class='message'>#{instance.error_message.first}</label></div>")
    end
end
于 2017-09-03T15:49:13.003 回答