开发者

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

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.la开发者_如何学Cbel :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?


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();


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜