简体   繁体   English

jQuery验证AJAX表单

[英]jQuery validation AJAX form

I'm trying to add validation to my ResetPassword function. 我正在尝试向我的ResetPassword函数添加验证。 validation its work fine, but I got another problem my ResetPassword function not going to work after I add validation.Can anyone direct me in the right direction? 验证它的工作正常,但是添加验证后,我遇到了另一个问题,我的ResetPassword函数无法正常工作。有人可以朝正确的方向指导我吗? thx. 谢谢。

HTML code: HTML代码:

<div class="PopUpBG">
  <div class="PopUp">
    <h3 class="modal-title">
      <span>Reset PAssword</span>
    </h3>
    <form id="form">

      <input type="email" name="ResetEmail" id="ResetEmail" placeholder="Email Adresse" required/>

      <input type="submit" class="btn btn-success" value="Send" onclick="ResetPassword(this)"/>

    </form>
  </div>

</div>

ResetPassword & validation code: ResetPassword和验证代码:

function ResetPassword(e) {

  var email = $("#ResetEmail").val();

  if ($("#form").validate()) {
    return true;
  } else {
    return false;
  }

  $(".PopUp").html("We have sent mail to you");

  $.ajax(
    {
      type: "POST",
      url: "/Account/loginRequestResetPassword",
      dataType: "json",
      data: {
        Email: email,
      },
      complete: function () {
        console.log("send");
        $(".PopUpBG").fadeOut();
      }
    })
}

The issue is because you're always exiting the function before you send the AJAX request due to your use of the return statement in both conditions of your if statement. 问题是因为由于在if语句的两种情况下都使用return语句,所以在发送AJAX请求之前总是退出该函数。

Change your logic to only exit the function if the validation fails: 更改逻辑以仅在验证失败的情况下退出函数:

function ResetPassword(e) {
  if (!$("#form").validate())
    return false;

  $.ajax({
    type: "POST",
    url: "/Account/loginRequestResetPassword",
    dataType: "json",
    data: {
      Email: $("#ResetEmail").val().trim(),
    },
    success: function() {
      console.log("send");
      $(".PopUp").html("We have sent mail to you");
      setTimeout(function() {
        $(".PopUpBG").fadeOut();
      }, 10000); // fadeout the message after a few seconds
    },
    error: function() {
      console.log('something went wrong - debug it!');
    }
  })
}

Also note that I amended the logic to only show the successful email message after the request completes. 还要注意,我修改了逻辑以仅在请求完成显示成功的电子邮件。 Your current code can show the 'email sent' message to the user, even though there is still scope for the function to fail. 您的当前代码可以向用户显示“已发送电子邮件”消息,即使该功能仍然存在失败的可能性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM