[英]How do I run this javascript code to validate my form in my html doc?
<!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>
U can use required
label for validations in each input tag
U可以在每个input tag
使用required
标签进行验证
add the onsubmit attribute to form tag 将onsubmit属性添加到表单标签
onsubmit="return validateForm();"
Update function validateForm to return true or false based on whether validation succeeds or fails. 更新函数validateForm以根据验证是否成功来返回true或false。 For more information see: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit 有关更多信息,请参见: https : //developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit
Move the onsubmit="return validateForm()"
from your submit
button to the form
element, where it belongs. 将 onsubmit="return validateForm()"
从submit
按钮移动到它所属的form
元素。 You also may change it to return validateForm(this)
: 您也可以将其更改为return validateForm(this)
:
<form name="Personal Information" action="" onsubmit="return validateForm(this)" >
Your javascript function is almost ok, just add a return true;
您的javascript函数几乎可以,只需添加return true;
at the end, get the form from the this
parameter we've added above and change the if condition: 最后,从上面添加的this
参数中获取表格,并更改if条件:
function validateForm (form) {
var formPi = form["firstname"].value;
if (formPi == null || formPi == "") { // <-- condition changed
alert("Please fill out your First Name!");
return false;
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.