2013-04-17 46 views
1

我正在验证注册页面上的表单,除了电子邮件验证有点碰到和错过之外,一切正常。表单不能在电子邮件JSON验证后提交

它工作正常,如果我只是验证它,以确保它是一个实际的电子邮件地址,但是当我尝试添加一个检查,看看它是否在使用以及我遇到问题。

验证本身工作正常,但表单一旦验证且未使用就不会提交。

这工作,并提交表单:

if(filter.test(a)){ 
     email.removeClass("field_error"); 
     emailInfo.text(""); 
     emailInfo.removeClass("error"); 
     return true; 
    } 

这工作,但形式不提交:

if(filter.test(a)){ 
     $.post('php/availability.php',{email: $('#email').val()}, function(emaildata){ 
      if(emaildata.exists){ 
       email.addClass("field_error"); 
       emailInfo.text("(Email address in use)"); 
       emailInfo.addClass("error"); 
      } else { 
       email.removeClass("field_error"); 
       emailInfo.text(""); 
       emailInfo.removeClass("error"); 
       return true; 
      } 
     }, 'JSON'); 
    } 

我难倒。

+0

什么是回来的emaildata? –

+0

它返回'存在'。确切地说{“exists”:true}。 – Adam

+0

如果它返回'{“exists”:true}',那么您的电子邮件地址正在使用中,并且表单不应该提交。也许我的理解不正确。 –

回答

1

这个问题与AJAX调用的异步性质有关(第一个'A')。

在第一个示例中,您将落入if区块,并立即返回true,我假定您允许您提交表单。

但是,在第二个示例中,您属于if块,但是您异步调用Web资源(availability.php)。您的代码进行AJAX呼叫(呼叫$.post()),然后立即到达if区块的末尾。不会返回True,所以表单不会提交。

你需要做的是:

  • exists===false逻辑移动到一个单独的函数;
  • 在您的if区块中,如果电子邮件有效,则调用该函数;
  • 你的函数查找表(使用jQuery说了),然后将其提交

所以修改后的代码可能看起来像:

if(filter.test(a)){ 
     $.post('php/availability.php',{email: $('#email').val()}, function(emaildata){ 
      if(emaildata.exists){ 
       email.addClass("field_error"); 
       emailInfo.text("(Email address in use)"); 
       emailInfo.addClass("error"); 
      } else { 
       submitForm(email, emailInfo); 
      } 
     }, 'JSON'); 
    } 

然后submitForm()确实是这样的:

function submitForm(email, emailInfo){ 
    email.removeClass("field_error"); 
    emailInfo.text(""); 
    emailInfo.removeClass("error"); 
    $('#theForm').submit(); 
} 

我想,那么,你应该看到你的表单提交。

希望这会有所帮助!

+0

感谢您的回答。但是,为了在表单提交中返回true,必须完成多个验证。这会覆盖这些并提交表单吗?或者这只是发送另一个提交电话,触发剩下的验证? – Adam

+0

如果您的提交依赖于现有的电子邮件,那么您应该将其封装在一个函数中,该函数在$ .post返回时会被调用。无论这是从上面创建的'submitForm'函数中调用的第二个函数,还是全部使用单个函数(即,将所有验证放在'submitForm'中)。需要记住的是你的'$ .post'调用是异步的,所以你的验证需要在'$ .post'返回后触发。我希望这有帮助。 –

+0

好的,我会记住这一点,看看我能做些什么。谢谢你的帮助! – Adam

相关问题