我正在尝试使用
HTML5模式和jQuery验证simpla联系表单,如下所示:
<form action="test.php" method="post" id="myForm">
<input type="text" name="name" id="name" class="form-control" pattern="[A-Za-z ]+" autofocus placeholder=" Please Enter Your Name" >
<input type="tel" name="phone" id="phone" class="form-control" pattern="\d{3}[\-]\d{3}[\-]\d{4}" autofocus placeholder="xxx-xxx-xxxx" >
<button type="submit" name="submit">Send Email</button>
</form>
这是我用来验证字段为空的jquery代码:
$(document).ready(function () {
$('#myform').submit(function () {
var abort = false;
$("div.alert").remove();
$('input[type="text"]').each(function () {
if ($(this).val() === '') {
$(this).after('<div class="err"><p>Phone Field Cant be Empty</p></div>');
abort = true;
}
}); // go through each required value
if (abort) {
return false;
} else {
return true;
}
}) //on submit
}); // ready
但是因为什么原因它没有验证表格!你能告诉我这里我做错了什么吗?
最佳答案 什么都不需要JS / jQuery.一切都可以通过HTML5验证.
使用输入字段中的必需项来确保值不为空并使用模式检查内容(就像您已经做过的那样).
<input ... required>
HTML
<?php
/* The form is POSTed to the same page to check the sumitted values */
print_r($_POST);
?>
<form action="" method="post" id="myForm">
<input type="text" name="name" id="name" class="form-control" pattern="[A-Za-z ]+" autofocus placeholder="Please Enter Your Name" required>
<input type="tel" name="phone" id="phone" class="form-control" pattern="\d{3}[\-]\d{3}[\-]\d{4}" placeholder="xxx-xxx-xxxx" required>
<button type="submit" id="send">Send Email</button>
</form>
最好的做法是使用on,如$(“#element”).on(“click”,function(){,而不是.click(function(){或.submit(function(){.