小编典典

在Ajax提交之前进行HTML5验证

ajax

这应该很简单,但是却让我发疯。我有一个用ajax提交的html5表单。如果输入的值无效,则会弹出一个提示您的信息。在运行ajax提交之前,如何检查条目是否有效?

形成:

<form id="contactForm" onsubmit="return false;">
  <label for="name">Name:</label>
  <input type="text" name="name" id="name" required placeholder="Name" />
  <label for="subject">Subject:</label>
  <input type="text" name="subject" id="subject" required placeholder="Subject" />
  <label for="email">Email:</label>
  <input type="email" name="email" id="email" required placeholder="email@example.com" />
  <label for="message">Message:</label>
  <textarea name="message" id="message" required></textarea>
  <input type="submit" id="submit"/>
</form>

提交:

$('#submit').click(function(){
    var name = $("input#name").val();
    var subject = $("input#subject").val();
    var email = $("input#email").val();
    var message = $("input#message").val();

    var dataString = 'email=' + email + '&message=' + message + '&subject=' + subject + '&name=' + name ;

    $.ajax({
        url: "scripts/mail.php",
        type:   'POST',
        data: dataString,
        success: function(msg){
            disablePopupContact();
            $("#popupMessageSent").css("visibility", "visible");
        },
        error: function() {
            alert("Bad submit");
        }
    });
});

阅读 421

收藏
2020-07-26

共1个答案

小编典典

默认情况下,jQuery对HTML5验证一无所知,因此您必须执行以下操作:

$('#submit').click(function(){
    if($("form")[0].checkValidity()) {
        //your form execution code
    }else console.log("invalid form");
});
2020-07-26