Learn how to add form validation for empty input fields with JavaScript.
<form name="myForm" action="/action_page.html" onsubmit="return validateForm()" method="post" required>
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
If an input field (fname) is empty, this function alerts a message, and returns false, to prevent the form from being submitted:
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
Try it Yourself »
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!