首页 > 解决方案 > 通过 Ajax 提交表单时验证失败

问题描述

我创建了一个带有 remote=>true 选项的表单。通常我使用客户端验证 gem 来处理错误。当我正常提交没有 ajax 客户端验证的表单时,它工作正常。当我使用 remote=>true(Ajax) 提交表单时,验证不起作用。当我提供正确的输入时,我的 ajax 工作正常。但是当我给出失败的验证输入时,它没有显示任何错误。

我的创建动作是

def create
@post = @topic.posts.new(post_params)
@post.user=current_user
respond_to do |format|
  if @post.save
    flash[:notice] = "Post sent Successfully"
    format.html {redirect_to topic_post_path(id: @post.id)}
    format.js
else
    format.html {render :new}
    format.json { render json: @post.errors, status: :unprocessable_entity }
    format.js   { render layout: false, content_type: 'text/javascript' }
  end
end
end

create.js.erb 是

$('#new_hide').fadeOut(1000)
$('#posts').empty();
$('.sort_paginate_ajax').append('<%= j render @post 
%>').ajaxSuccess(alert('you have created a post'))

我有 ajax 要求在索引中创建一个新帖子

<%= link_to "Add Post",new_topic_post_path,remote: true,id: "post"%>
<div class="row sort_paginate_ajax">
<%= render @posts %>
</div>

我的 new.js 是

$('#post').hide().after('<%= j render :partial => "formm", :locals => { :button_label => "Create Post", :topic => @topic ,:post => @post} %>')
$('#new_form').enableClientSideValidations();

我的部分表格是

<div id="form-modal">
<%= form_for [topic,post], validate: true,:html=> {multipart: true}, 
remote: true do |f| %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title , validate: { presence: true } %></p>
<%= f.label :description %><br>
<%= f.text_area :description ,validate: true ,required: true%>
</p>
 <p>
<%= f.submit button_label, class: "btn btn-success",id: "submit" %>
 </p>
<% end %>
 </div>

我正在使用 rails 5.1.6 和 ruby​​ 2.5.1p57

标签: jqueryajaxruby-on-rails-5

解决方案


推荐阅读