在html表单中进行年龄验证时遇到问题



我想打印出输入正确的段落标记,只闪烁一秒钟,然后就消失了。

<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>HOMEWORK</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
</head>
<body>
<h1 style="text-align:center">FORM FILL</h1>
<p>Kindly fill in the following details as mentioned below : </p>
<form name="FORM"  onsubmit="checkform()">
<!---- <label for="FName">Name :</label><br>
<input type="text" id="FName" name="FName"><br><br>--->
<label for="Age">Age :</label><br><br>
<input type="text" id="Age" name="Age"><br><br>
<input type="button" value="Submit">
</form><br><br>
<p id="demo"></p>
<script>
function checkform() 
{
var x, text;
x = document.forms["FORM"]["Age"].value;
if (x<1||x>100||x==''||isNaN(x))
{
alert("Invalid Age !!!");
text = "Input not valid";
// return false;
} 
else
{
text = "Input OK";
// return true;
} 
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>

有人能告诉我我做错了什么吗?验证表单的最短方法是什么?

您需要防止重定向页面对您的代码进行一些更改检查一次:

<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>HOMEWORK</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
</head>
<body>
<h1 style="text-align:center">FORM FILL</h1>
<p>Kindly fill in the following details as mentioned below : </p>
<form name="FORM"  onsubmit="return mySubmitFunction(event)">
<!---- <label for="FName">Name :</label><br>
<input type="text" id="FName" name="FName"><br><br>--->
<label for="Age">Age :</label><br><br>
<input type="text" id="Age" name="Age"><br><br>
<input type="submit" value="Submit">
</form><br><br>
<p id="demo"></p>
<script>
function mySubmitFunction(e) { 
e.preventDefault(); 
try {
checkform();
} catch (e) {
throw new Error(e.message);
}
return false;
}
function checkform() 
{
var x, text;
x = document.forms["FORM"]["Age"].value;
if (x<1||x>100||x==''||isNaN(x))
{
alert("Invalid Age123 !!!");
text = "Input not valid";
// return false;
} 
else
{
text = "Input OK";
// return true;
} 
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>

希望这能有所帮助!

相关内容

  • 没有找到相关文章

最新更新