client_side_validations (3.1.0) not working when new form is added to the DOM

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-01 05:35:43

问题


I'm using Rails 3.1.0rc4 and client_side_validations 3.1.0. Everything works perfectly so long as the form is rendered in the main request. However, if the form itself is added to the page via javascript, then submitting the form results in server side validation. I suspect that the problem is that when the form is added to the page via javascript I need to "bind" the client side validation functionality to it somehow.

For example, suppose I have a simple form where you can post a new job listing:

#jobs/new.html.erb
<%= form_for [@job], :validate => true  do |f| %>

  <%= render :partial => 'common/form_errors', :locals => {:record => @job} %>

  <div class="field">
      <%= f.label :title %>
      <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :description %>
    <%= f.text_field :description %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

and the following validations in my model:

class Job < ActiveRecord::Base
  validates_presence_of :title, :description
end

If I visit this form by visiting the new_job_path in my browser, my client side validations work great.

However, if I insert this form into another page (for example the jobs_path index page) as follows:

#jobs/index.html.erb
<%= render @jobs %>

<div id="form-job-new"> </div>

<%= link_to 'New Job', new_job_path, :remote =>true %>

and:

#jobs/new.js.erb
$('#form-job-new').append("<%= escape_javascript render(:file => 'jobs/new.html.erb') %>");

then when the form is submitted, the validations are applied server side.

Any idea what I'm missing?


回答1:


Found the answer in the javascript source code for this gem:

// Main hook
// If new forms are dynamically introduced into the DOM the .validate() method
// must be invoked on that form
$(function() { $('form[data-validate]').validate(); })

So, in my particular case, I needed to do:

#jobs/new.js.erb
$('#form-job-new').append("<%= escape_javascript render(:file => 'jobs/new.html.erb') %>");
$('form[data-validate]').validate();



回答2:


Depending on how much you use ujs (i do a lot) it might make more sense to do something like this instead of calling the validate method in every ujs file.

$('body').bind("ajax:success", function() {
   if($('form[data-validate]').length){
      $('form[data-validate]').validate();
   }
});

or coffeescript

$("body").bind "ajax:success", ->
  $("form[data-validate]").validate()  if $("form[data-validate]").length


来源:https://stackoverflow.com/questions/6750174/client-side-validations-3-1-0-not-working-when-new-form-is-added-to-the-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!