2011-05-03 66 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 
}); 

希望这可以帮助你找到一个解决方案,而不仅仅是更多的相同(也只是意识到这个问题已经过去了一年,但我已经写了这么...)