remote:true form避免js字段验证

时间:2014-08-19 15:17:04

标签: javascript ruby-on-rails validation client-side-validation

这是我的表格:

<%= form_for [@company,@company_branch], :html => { :onsubmit => "return validateName();" }, remote: true do |f| %>
    <%= f.text_field :name %>
    ...

&#34; validateName&#34;当我不使用远程呼叫时,验证工作正常。但是,如果它是远程的,表单仍然会被提交,即使我的验证返回false。

这是用于验证的.js:

function validateName() {
    var name = document.getElementById('name');
    if( name.value == "" ) {
        highlightError(name, "Please provide a name");
        return false;
    }

    return ( true );

}

2 个答案:

答案 0 :(得分:0)

我碰到了同样的事。我目前还没有找到解释,但根据我的实验,远程执行表单的帖子与onsubmit函数的返回值无关。 我在服务器端使用了表单验证,并发回了js以进行验证错误处理。

更新。 “在Rails 2中?至少3,form_form,:remote =&gt; true覆盖:onsubmit =&gt;'func();'方法来进行实际的表单提交。如果你想在它之前绑定一些东西到你的表单获取提交(或在期间或之后!),使用jQuery.bind()绑定表单,然后观察AJAX回调函数以执行您需要的操作。

<script type="text/javascript>
  function get_address_information() {
    // check jquery for all the possible callbacks. there is also success and error. compete get calls after both success and error
    var pars = 'param1=x&amp;param2=y&amp;param3=z';
    $.ajax({ type: "POST",
      url: "/get_invite_address",
      data: pars, dataType: 'script',
      beforeSend: function() {
        // do your before send checking here
      },
      complete: function(data, status) {
        // do some post processing ehre
      }
    });
  }
</script>"

形成source

答案 1 :(得分:0)

变体工作解决方案是将验证绑定到ajax:beforeSend事件,函数beforeOneClick返回false或true:

$('form')
 .bind('ajax:success', function(evt, data, status, xhr) {
  console.log('success: ' + xhr + '/' + status + '/' + data);
 })
 .bind("ajax:beforeSend", function(evt, xhr, settings){
  return beforeOneClick();
 })
 .bind('ajax:complete', function(evt, xhr, status){
  console.log('complete');
 })
 .bind("ajax:error", function(evt, xhr, status, error){
  console.log('error:' + xhr + '/' + status + '/' + error);
 });