gpt4 book ai didi

javascript - 提交时的表单验证不起作用

转载 作者:行者123 更新时间:2023-11-27 23:19:18 26 4
gpt4 key购买 nike

嗨,我正在阅读如何验证 html 表单,我的所有验证器客户端都在工作模式和类型。问题是当我按提交时,JavaScript 验证不会运行。这是我的代码:

<script language="javascript">

function validateForm()
{
var xa = document.forms["regform"]["password"].value;
var xb = document.forms["regform"]["password2"].value;
var xc = document.forms["regform"]["email"].value;
var xd = document.forms["regform"]["email2"].value;
if (xa == xb && xc == xd){
return true; }
else{ return false; alert("Please enter a valid captcha code");}
}

$(document).ready(function(e) {
try {
$("body select").msDropDown();
} catch(e) {
alert(e.message);
}
});

</script>

它们的形式:

<form name="regform" onsubmit="return validateForm();" action="actions/register_acc.php" method="post">

<input type="password" name="password" class="input-style" required="required">
<input type="password2" name="password" class="input-style" required="required">

<input name="email" class="input-style" placeholder="your@email.com" required="required" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$">
<input name="email2" class="input-style" placeholder="your@email.com" required="required" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$">

<input type="submit" value="ok">

</form>

在表单中我还有这些:

<select name="selectname" id="webmenu">
<option value="1">1</option>
<option value="2">2</option>
</select>

在头部这些:

<script src="js/msdropdown/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/msdropdown/jquery.dd.min.js" type="text/javascript"></script>

最佳答案

问题出在 validateForm 方法本身,特别是在 else block 中。您在 alert 调用之前返回 false。交换这两个调用,您应该会看到出现警报消息。

为了清楚起见,我会更改警报框中的消息,因为它与您正在验证的字段不直接相关。

function validateForm()
{
var xa = document.forms["regform"]["password"].value;
var xb = document.forms["regform"]["password2"].value;
var xc = document.forms["regform"]["email"].value;
var xd = document.forms["regform"]["email2"].value;
if (xa == xb && xc == xd){
return true;
}
else {
alert("Please enter a valid captcha code");
return false;
}
}

查看此 Fiddle

关于javascript - 提交时的表单验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35528802/

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