简体   繁体   English

验证之前提交JQuery表单

[英]Jquery form submitting before validation

I want to validate a form for inputs with the 'required' attributes but it appears that "e.preventDefault()" is not working. 我想验证具有'required'属性的输入表单,但看来“ e.preventDefault()”无法正常工作。 The form submits and the POST succeeds but with the unvalidated data and I can't find where the problem is. 表单提交,并且POST成功,但是有未经验证的数据,我找不到问题所在。

<form>
  <label for="name" class="control-label">Name</label>
  <input type="text" id="name" class="form-control" required>
  <label for="phone" class="control-label">Phone Number</label>
  <input type="text" id="phone" class="form-control" required>
  <label for="email" class="control-label">Email address</label>
  <input type="email" id="email" class="form-control" required>
  <div id="form-response"></div>
  <button class="btn btn-lg btn-primary btn-block" id="submit" type="submit" style="background-color:#28547C;">Request Appointment</button>
</form>

JS: JS:

$(document).ready(function() {
    $("#submit").click(function(e) {
      e.preventDefault();
      var name = $("#name").val(),
        email = $("#email").val(),
        phone = $("#phone").val()
      $.ajax({
        type: "POST",
        url: 'https://a2xvt72c0c.execute-api.us-west-2.amazonaws.com/prod',
        contentType: 'application/json',
        data: JSON.stringify({
          'name': name,
          'phone':phone,
          'email': email
        }),
        success: function(res) {
          $('#form-response').html('<div class="alert alert-info" role="alert">Thank you! Appointment request has been sent. We will contact you soon. </div>');
        },
        error: function() {
          $('#form-response').html('<div class="alert alert-info" role="alert">Something went wrong... We are working on it!</div>');
        }
      });
    })
  });

JS Fiddle: https://jsfiddle.net/yhgz55y0/ JS小提琴: https//jsfiddle.net/yhgz55y0/

Right now you are using a click event and not a submit event. 现在,您使用的是点击事件,而不是提交事件。 If you switch it to: 如果将其切换为:

$("#submit").submit(function(e) {...

the validation works. 验证有效。

Your form is submitting because you are calling the $.post() immediately without stopping. 您正在提交表单,因为您正在不停地立即调用$.post() You want to run validation against your name , email and phone variables and if any are not valid, return early or put the entire thing into an if block. 您想针对您的nameemailphone变量运行验证,如果任何无效,请尽早return或将整个内容放入if块中。

What e.preventDefault() does is prevents the browser built-in actions. e.preventDefault()作用是防止浏览器内置操作。 But as your form has no action or target properties, you are effectively canceling a no-op, hence why this is not behaving as you expect it to. 但是由于您的表单没有动作或目标属性,因此您实际上是在取消无操作,因此为什么这样做没有您期望的那样。

preventDefault is a function that prevents a normal task from executing. preventDefault是防止正常任务执行的功能。 Here you prevent the click on a button. 在这里,您可以防止单击按钮。 A button doesn´t have a function in this form so there won´t be any difference. 按钮没有这种形式的功能,因此不会有任何区别。 You want to prevent de form from submiting. 您要防止提交表单。 If you change your code to this: 如果将代码更改为此:

 $(document).ready(function() { $("form").submit(function(e) { e.preventDefault(); var name = $("#name").val(), email = $("#email").val(), phone = $("#phone").val() $.ajax({ type: "POST", url: 'https://a2xvt72c0c.execute-api.us-west-2.amazonaws.com/prod', contentType: 'application/json', data: JSON.stringify({ 'name': name, 'phone':phone, 'email': email }), success: function(res) { $('#form-response').html('<div class="alert alert-info" role="alert">Thank you! Appointment request has been sent. We will contact you soon. </div>'); }, error: function() { $('#form-response').html('<div class="alert alert-info" role="alert">Something went wrong... We are working on it!</div>'); } }); }) }); 

This assuming you only have 1 form on your page. 假设您的页面上只有1个表单。 This will prevent the form from submiting. 这将阻止表单提交。

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

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