2016-08-22 22 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." 
);