client_side_validations(3.1.0)当新的形式加入到DOM不工作 [英] client_side_validations (3.1.0) not working when new form is added to the DOM

查看:169
本文介绍了client_side_validations(3.1.0)当新的形式加入到DOM不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Rails 3.1.0rc4和client_side_validations 3.1.0。一切完美的作品,只要形式在主请求呈现。但是,如果窗体本身是通过JavaScript添加到页面,然后提交表单结果在服务器端验证。我怀疑的问题是,当表单通过JavaScript添加到页面,我需要绑定的客户端验证功能,它在某种程度上。

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

如果我通过访问new_job_path在我的浏览器访问这个表,我的客户端验证工作带来极大的。

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

不过,如果我插入这种形式进入另一个页面(例如jobs_path索引页)如下:

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 %>

#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?

推荐答案

找到了答案,在JavaScript源$ C ​​$ C为这种宝石:

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

这篇关于client_side_validations(3.1.0)当新的形式加入到DOM不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆