如何验证Ajax表单提交(remote_form_tag)?

时间:2010-08-12 04:03:21

标签: javascript ruby-on-rails ajax haml

我有一个类似

的ajax邮件表单
  - form_remote_tag :url=>mails_path,:condition=>"validate_mail()", :html => {:id=>"mailform",:method => :post, :class => 'ajax',:style=>"padding:15px;" } do |form|
    .gimmespace 
      Naam 
      %br
      = text_field_tag :name,params[:name],:class=>"title required"
    .gimmespace 
      Telefoonnummber 
      %br
      = text_field_tag :phone,params[:phone],:size=>25,:class=>"title"
    .gimmespace 
      Mailadres 
      %br
      = text_field_tag :email,params[:email],:size=>30,:class=>"title required"
    .gimmespace 
      Onderwerp 
      %br
      = text_field_tag :subject,params[:subject],:class=>"title required"
    .gimmespace
      Boodschap 
      %br
      = text_area_tag :message,params[:message],:rows=>10,:cols=>45,:class=>"title required"
    .gimmespace
      = submit_tag "Verstuur",:id=>"mailsubmit",:class=>"sendBtn"
      %button{:onclick=>"$.fn.colorbox.close();"} Annuleer

以上代码在HAML中。它将ajax表单提交给控制器。我必须在提交之前验证字段。所以,我尝试了几个东西。我读了这篇文章http://hillemania.wordpress.com/2006/09/18/rails-ajax-pre-submit-form-validation/并在回调测试javascript函数之前进行了验证。这是javascript验证功能。

function validate_mail() {
        alert("Your Name, Email, Subject and Body Content are Required !");
        return false;

}

根据上面的函数,它以任何方式返回false,并且表单不应该被提交但是,它提交得非常好。还有其他方法,请帮忙。

1 个答案:

答案 0 :(得分:0)

我认为您要使用:condition选项而不是:before选项。像这样:

  - form_remote_tag :url=> mails_path, :condition => "validate_mail()", ...

然后,如果您的condition函数返回false,则不应提交表单。

当然,您需要修改validate_mail()函数,实际测试每个表单字段不为空:

if ($('name').value == '' || $('phone').value == '' || ... ) {
  alert('Something was blank...');
  return false;
} else {
  return true;
}

我的原型语法生锈 - 这应该会让你走上正确的轨道。

相关问题