Remote: true形式避免js字段验证

remote: true form avoids js field validation

本文关键字:js 字段 验证 true Remote      更新时间:2023-09-26

这是我的表单:

<%= 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 );
}

我也撞了。我目前还没有找到一个解释,但根据我的实验,远程做表单的post独立于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>"

形成源

变体工作解决方案是将验证绑定到ajax: beforeend事件,函数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);
 });