2012-04-06 112 views
0

我想创建一个基于数据库值的特殊邮政编码验证。因此,我对AJAX检查值:ajax jquery表单验证总是验证错误

jQuery.validator.addMethod("validate_country_from", function(value, element) 
{ 
    $.ajax({ 
     type: "POST", 
     url: "ajax.php", 
     data: "action=validate_countryzip&direction=1&zip=" + 
     escape(document.getElementById("zip_from").value) + "&country=" + 
     escape(document.getElementById("country_from").value), 
     async: false 
    }).done(function(msg) 
    { 
     if(msg == "true") 
     { 
     return true; 
     } 
     else 
     { 
     return false; 
     } 
    }); 
}, addressError); 

而且我对这些规则的规则分配功能:

zip_from: { 
    required: true, 
    validate_country_from: true 
}, 
country_from: { 
    required: true, 
    validate_country_from: true 
}, 

Ajax请求工作正常,并且它完成同步的,返回的值也是正确的,但我的验证仍然告诉我这两个字段有错误。

我希望有人能帮助...

回答

0

谢谢你的答案,但我找到了原因:我的“完成”功能的值返回到AJAX请求采取行动,而不是验证方法(匿名委托是伟大的,但有时候确实很混乱) 。

正确的版本是这样的:

jQuery.validator.addMethod("validate_country_from", function(value, element) 
{ 
    var test = $.ajax({ 
     type: "POST", 
     url: "ajax.php", 
     data: "action=validate_countryzip&direction=1&zip=" + 
     escape(document.getElementById("zip_from").value) + "&country=" + 
     escape(document.getElementById("country_from").value), 
     async: false 
    }).done(function(msg) 
    { 
    }); 

    if(test.responseText == "true") 
    { 
     return true; 
    } 
    else 
    { 
     return false; 
    } 
}, addressError); 

然而,这还不是最终的解决方案,因为它没有抓住任何错误等。

1

我觉得你有你的混合的jQuery AJAX方法一点点。我在get()之前见过done()之前使用过,但从未在ajax()之后使用过。尝试

jQuery.validator.addMethod("validate_country_from", function(value, element) 
{ 
    $.ajax({ 
     type: "POST", 
     url: "ajax.php", 
     data: "action=validate_countryzip&direction=1&zip=" + 
     escape(document.getElementById("zip_from").value) + "&country=" + 
     escape(document.getElementById("country_from").value), 
     async: false, 
     success: function(msg){ 
      if(msg == "true") 
      { 
       return true; 
      } 
      else 
      { 
       return false; 
      } 
     }, 
     error: function(x, s, e){ 
      return false; 
     } 
    }); 
}, addressError);