[英]Add validation to HTML5 required fields
我在輸入元素上使用HTML5的required
屬性,然后選擇框和PHP進行驗證。
如果未填寫required
字段,如何顯示警報? 我嘗試使用onsubmit()
但無論如何都處理了表單,並且未顯示任何警報。
如果用戶的瀏覽器支持html5,則即使沒有填寫所有必填字段,他也無法提交表單。
通常,您可以像這樣阻止表單在jQuery中提交:
$('#yourformselector').submit(function(event) {
$(this).find('[required="required"]').each(function() {
if (!$(this).val().length) {
event.preventDefault();
return false;
}
});
});
如果您使用的是現代/較新的網絡瀏覽器,則默認的瀏覽器警報應自動顯示。
或嘗試:
$(document).ready(function() {
$('form').submit(function() {
var incomplete = $('form :input').filter(function() {
return $(this).val() == '';
});
//if incomplete contains any elements, the form has not been filled
if(incomplete.length) {
alert('please fill out the form');
//to prevent submission of the form
return false;
}
});
});
您可以使用checkValidity(),它會嘗試與像模式,最小值,最大值,需要等屬性來驗證按照此鏈接進入更深這里
function myFunction() { var inpObj = document.getElementById("id1"); if (inpObj.checkValidity() == false) { alert('invalid input') } else { alert('valid input') } }
<input id="id1" type="number" min="100" max="300" required> <button onclick="myFunction()">OK</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.