在Ajax提交之前进行HTML5验证

这应该很简单,但是却让我发疯。我有一个用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");

}

});

});

回答:

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

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

if($("form")[0].checkValidity()) {

//your form execution code

}else console.log("invalid form");

});

以上是 在Ajax提交之前进行HTML5验证 的全部内容, 来源链接: utcz.com/qa/398037.html

回到顶部