gpt4 book ai didi

javascript - 即使验证失败,表单也会提交

转载 作者:行者123 更新时间:2023-11-30 08:57:58 24 4
gpt4 key购买 nike

我只是在学习 Javascript,如果我的问题看起来很愚蠢,请多多包涵...

我需要创建一个 html 表单并在字段上运行一些验证。无论字段是否填写正确,我在点击提交按钮时都会收到错误 404。如果我复制/粘贴别人的代码来做同样的事情,它就可以正常工作。文件“somepage.php”不存在,但对于其他人的代码也不存在。

我在 CodeLobster 中编码,然后在 Notepad++ 中编码。没有变化。

这是 HTML 文件,再往下是 javascript 文件的内容...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>

<head>
<title>Registration Form</title>
<script type="text/javascript" src="js.js"></script>
</head>

<body>
<form action="somepage.php" onsubmit="checkLogin()" method="post" >

Name: <input type="text" name="name" id="nameF" /><br />
Email: <input type="text" name="email" id="emailF" /><br />

<input type="submit" value="Submit" name="submit" />

</form>
</body>

</html>

function checkLogin()
{
var emailPattern = /^\w+([\.\-]?\w+)*@\w+([\.\-]?\w+)*\.[a-z]{2,6}$/i;
var email = document.getElementById('emailF').value;
var name = document.getElementById('name').value;

if (email == "")
{
alert("Please enter valid email address.");
document.getElementById('emailF').select();
document.getElementById('emailF').focus();
return false;
} else if (name == "") {
alert("Please enter your name.");
document.getElementById('nameF').select();
document.getElementById('nameF').focus();
return false;
} else if (!emailPattern.test(email)) {
alert("The email address entered is invalid");
document.getElementById('emailF').select();
document.getElementById('emailF').focus();
return false;
}
return true;
}

最佳答案

您的问题不是页面丢失(您已经知道)。问题是您的表单无论如何都会提交,即使验证失败也是如此。

form.onsubmit 方法应该返回false 以阻止表单提交。换句话说,这:

<form action="somepage.php" onsubmit="checkLogin()" method="post" >

应该是:

<form action="somepage.php" onsubmit="return checkLogin()" method="post" >

当然,如果表单确实通过验证,它将正确地继续到 somepage.php,此时您会收到 404 错误,因为页面没有不存在。

关于javascript - 即使验证失败,表单也会提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11788002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com