【问题标题】:remote: true form avoids js field validationremote: true form 避免 js 字段验证
【发布时间】:2014-08-19 15:17:04
【问题描述】:

这是我的表格:

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

当我不使用远程调用时,“validateName”验证工作正常。但是如果远程操作,表单仍然会被提交,即使我的验证返回 false。

这是用于验证的 .js:

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

    return ( true );

}

【问题讨论】:

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


    【解决方案1】:

    我也遇到了同样的事情。目前我还没有找到解释,但是根据我的实验,远程做表单的发布独立于 onsubmit 函数的返回值。 我在服务器端使用了表单验证,并返回一个 js 进行验证错误处理。

    已更新。 “在 Rails 2? 和至少 3 中,form_form, :remote => true 会覆盖 :onsubmit => '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

    【讨论】:

      【解决方案2】:

      变体工作解决方案是绑定一个验证到 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);
       });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-04
        • 2023-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多