ajax jquery表单验证总是验证false

时间:2012-04-06 19:47:51

标签: jquery ajax validation

我正在尝试根据数据库值创建特殊的邮政编码验证。因此我通过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
   }).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请求工作正常,并且它是同步的,返回的值也是正确的,但我的验证仍告诉我这两个字段有错误。

我希望有人能帮忙......

2 个答案:

答案 0 :(得分:1)

我认为你在那里混合了你的jQuery AJAX方法。我之前看过done() get()之后使用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); 之后从未使用{{1}}。尝试

{{1}}

答案 1 :(得分: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);

然而,这不是最终解决方案,因为它没有捕获任何错误等等。

相关问题