【问题标题】:Validate input before Ajax Call在 Ajax 调用之前验证输入
【发布时间】:2016-12-27 20:53:36
【问题描述】:

我在用户输入他的电子邮件的地方弹出这个:

<form class="form" id="PopupEmailForm">
            <div id="PopupEmail" class="modal fade" role="dialog">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-body">
                            <a data-dismiss="modal">Close</a>
                            <p>Enter The Email:</p>
                            <input type="email" id="EmailInput" name="Email" placeholder="name@example.com" required="required" />
                            <input type="submit" value="Send" id="PopupEmailSubmit" />
                        </div>
                    </div>
                </div>
            </div>
        </form>

在提交时,我正在执行以下操作:

$('#PopupEmailSubmit').click(function () {

    $.ajax({
        type: "POST",
        url: "controller/action",
        data: {
            Email: $('#EmailInput').val()
        },
        beforeSend: function () {
            $("#PopupEmailSubmit").prop('disabled', true); 
            $.growl({
                title: "Email Confirmation",
                message: "Sending Email..."
            });
        },
        success: function (res) {
            if (res) {
                $.growl.notice({ title: "Email Confirmation", message: "Email Sent!" });
                $('#PopupEmail').modal('hide');
            } else {
                $.growl.error({ title: "Email Confirmation", message: "Email Not Sent. Try again later." });
            }
            $("#PopupEmailSubmit").prop('disabled', false); // enable button

        }
    });
});

我想在调用 ajax post 方法之前对电子邮件输入进行验证。

我希望验证类似于(内联)&lt;input type="email"/&gt; 的 HTML5 验证

谁能帮忙

【问题讨论】:

    标签: javascript jquery html ajax


    【解决方案1】:

    由于您使用的是表单,您也可以在表单的submit 事件中执行此操作,而不是单击按钮

    $('#PopupEmailForm').submit(function (event) {
      event.preventDefault();
      //ajax call here
    
    });
    

    【讨论】:

      【解决方案2】:

      试试这个:

      $('#PopupEmailSubmit').click(function () {
          var email = $('#EmailInput').val();
          // create a validation rule
          if(validation successful)
          {
              // make ajax call
          }
          else
          {
              // show alert
          }
      });
      

      【讨论】:

        猜你喜欢
        • 2016-01-27
        • 2020-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-07
        • 2015-10-29
        • 1970-01-01
        相关资源
        最近更新 更多