client_side_validations (3.1.0) not working when n

2019-02-18 14:36发布

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?

2条回答
Deceive 欺骗
2楼-- · 2019-02-18 14:55

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();
查看更多
混吃等死
3楼-- · 2019-02-18 15:21

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
查看更多
登录 后发表回答