2011-05-03 63 views
1

答案我已經注意到,有時我的驗證代碼工作錯誤:jQuery的遠程驗證不會等待來自服務器

var $validator = $("#checkoutForm").validate(); 

... 

if (!$validator.element($sameShippingAddress)) { 
    ...  
} 

調試使用Firebug顯示,有時$ validator.element($ sameShippingAddress)將返回undefined(我猜它只是不等到返回響應),並假設爲假,即使元素是有效的。

如果這樣的代碼添加if語句,一切工作之前罰款:

while (validator.element($sameShippingAddress) !== undefined) { 

} 

問題是,如果這是正確的解決方案,有沒有更好的方式來處理與驗證插件本身的問題?

更新:我使用http://bassistance.de/jquery-plugins/jquery-plugin-validation/

+0

我一直拉我的頭髮問題。你的問題提供了一個臨時解決方案('while'循環),但很高興知道是否有更好的解決方案。 – 2011-06-09 06:47:00

回答

0

Obiously,它不是最好的解決辦法。相反,添加

如果(!$ validator.element($ sameShippingAddress)){ ...
}

在Ajax回調函數

+0

不知道,如果我明白你提供什麼。我想我需要指定更確切的是什麼:元素是http://docs.jquery.com/Plugins/Validation/Validator/element和遠程驗證是http://docs.jquery.com/Plugins/Validation/Methods /遠程和遠程驗證器配置由asp.net mvc生成。 – Giedrius 2011-05-03 11:38:55

1

驗證變量上的無限while循環不是一個好的選擇。而是使用下面使用JavaScript計時器的代碼。您可以在validate()方法之後顯示動畫處理/服務器響應圖形。

var validator = $('#resetpassword').validate({///your code...}) 

    doTimer(); 

    function timedCount() 
    { 
     t=setTimeout("timedCount()",1000); 
    } 

    function doTimer() 
    { 
    if (validator === undefined) 
     { 
     timedCount(); 
     } 
    } 

if(validator==true) 
    $('#form').ajaxSubmit(options); 
1

很難告訴你如何處理成功提交,或者如果您使用的CSS類來表示必填字段,但下面是它是如何在demo的插件來完成:

$.validator.setDefaults({ 
    // code to be executed on submit 
submitHandler: function() { alert("submitted, replace this with your server request");} 
}); 

$().ready(function() { 
    // validate the comment form when it is submitted 
     // use css class .required for fields you want the validator to check 
     // if your form is valid then it is handled by the submitHandler 
     // if not the plugin displays error messages 
    $("#checkoutForm").validate(); 
    //validate can take a block for custom validation and error messages 
}); 

希望這可以幫助你找到一個解決方案,而不僅僅是更多的相同(也只是意識到這個問題已經過去了一年,但我已經寫了這麼...)