<!DOCTYPE html>
<head></head>
<body>
<script>
function validateForm (){
var formPi = 0
var formPi = document.forms["Personal Information"]["firstname"].value;
if(formPi == null ){
alert("Please fill out your First Name!");
return false;
}
}
</script>
<form name="Personal Information" action="" >
<fieldset>
<legend>Personal information:</legend>
<br>
First name:<br>
<input type="text" name="firstname" value="" >
<br>
Last name:<br>
<input type="text" name="lastname" value="" >
<br>
Email Address:<br>
<input type="text" name="Email Address" value="" >
<br>
<br><br>
<input type="submit" value="Submit" onsubmit="return validateForm()">
<!-- The for is meant to be validated once the subit button has been clicked-->
</fieldset>
</form>
</body>
</html>
最佳答案
<!DOCTYPE html>
<html>
<body>
<form action="demo_form.asp" method="post">
<input type="text" name="fname" required>
</form>
<p>If you click submit, without filling out the text field,
your browser will display an error message.</p>
</body>
</html>
您可以在每个输入标记
中使用required
标签进行验证
关于javascript - 如何运行此 JavaScript 代码来验证 html 文档中的表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34002980/