2016-08-22 75 views
0

我发现这个链接的其他 jQuery validate + AJAX e-mail availiability checkjQuery验证阿贾克斯犯规重新验证

提问者表示他们希望执行成功的一些东西,但你出来再次更改值和标签后场不会重新验证。

用户Blowhard博士说这是因为它们覆盖了远程方法的成功回调。但他没有举例说明如何处理这个问题。相反,他有一个SubmitHandler绑定到验证选项。那么,我该如何做几件事,然后返回真或假呢?例如,如果我找到了电子邮件地址,我会返回一些已存档的数据并禁用这些表单字段。

$("#userForm").validate({ 
onfocusout: function (element) { 
    this.element(element); 
}, 
onkeyup: false, 
rules: { 
    email: { 
     required: true, 
     email: true, 
     remote: { 
      url: 'ajax/checkEmail.php', 
      type: 'post', 
      data: { 
       email: function() { 
        return $('#email').val(); 
       } 
      }, 
      success: function(data) { 
       if(data.status == 1) { 
        $('#affcode').val(data.affCode).attr("disabled", true); 
        $('#userID').val(data.userID); 
        $('#password, #password2').attr("disabled", true); 
        return true; 
       } else { 
        $('#password, #password2, #affcode').removeAttr("disabled"); 
        return true; 
       } 
      } 
     } 
    }, 
messages: { 
    affcode: { 
     required: "Please enter a custom affiliate code.", 
     regx: "Affiliate codes must start with a LETTER." 
    } 
} 
}); 

我的PHP是这样的:

$res = PDOWrapper::instance()->select('accounts', array("email" => $_REQUEST['email'])); 

if(count($res) > 0) { 
    $return['status'] = 1; 
    $return['affCode'] = $res[0]['affCode']; 
    $return['userID'] = $res[0]['aKey']; 
} else { 
    $return['status'] = 0; 
} 


echo json_encode($return); 

回答

0

的最好方法是创建一个自定义规则。添加变量响应非常重要;就在addMethod之前。你只需要申报一次。

var response; 
$.validator.addMethod(
    "checkAffiliate", 
    function(value, element) {   
     $.ajax({ 
      type: "POST", 
      url: "ajax/checkAffiliate.php", 
      data: { 
        email: function() { 
         return $('#email').val(); 
        }, 
         affcode: function() { 
         return $('#affcode').val(); 
        }, 
      }, 
      dataType: 'json', 
      success: function(data) 
      { 
       if(data.status == 0) { 
        response = false; 
       } else { 
        //Do some stuff here 
        response = true; 
       }   
      }, 
      async: false 
     }); 
     return response; 
    }, 
    "Affiliate Code is already in use." 
);