gpt4 book ai didi

JavaScript 验证表单的考试编号

转载 作者:行者123 更新时间:2023-12-03 12:37:11 28 4
gpt4 key购买 nike

我目前正在使用 html 来编写“表单条目”代码。我还使用 JavaScript 验证来验证表单的输入。到目前为止,我有“姓名”、“科目”和“考试号”。但是,我的验证不适用于我的考试号。它几乎完成了,但是当我测试我的考试号验证时,我遇到了错误。测试时,我在考试编号中输入“abcd”,这应该表明考试编号只能是数字。确实显示了一条错误消息(这是正确的),但在单击“确定”尝试其他输入后,表单似乎已提交。如果有人可以帮助我验证考试号,这样输入只能是四位数字,并且在出现错误消息后,不会提交表格并允许用户重新输入考试号,那就太好了。

这是我的代码:

<head>

<title>Exam Entry</title>

<script language="javascript" type="text/javascript">

function validateForm(e) {

var result = true;
var msg="";

if (document.ExamEntry.name.value=="") {
msg+="You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}

if (document.ExamEntry.subject.value=="") {
msg+="You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}

var regex = /^\d{4}$/;
if (document.ExamEntry.Examination_number.value == "") {
msg+="You must enter your examination number";
} else if (isNaN(document.ExamEntry.Examination_number.value)) {
msg+="Examination number should only contain digits";
} else if (!regex.test(document.ExamEntry.Examination_number.value)) {
msg+="Examination number should contain exactly 4 digits";
}

if (msg != "") {
alert(msg);
}

return result;
}
</script>



</head>

<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html" onsubmit="return validateForm();">
<table width="60%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<td id="Examination_number">Examination number</td>
<td><input type="text" maxlength="4" name="Examination_number" /></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>

</html>

最佳答案

一旦验证完成,如果错误,则必须返回 false,

var regex = /^\d{4}$/;
if (document.ExamEntry.Examination_number.value == "") {
msg+="You must enter your examination number";
result = false;
} else if (isNaN(document.ExamEntry.Examination_number.value)) {
msg+="Examination number should only contain digits";
result = false;
} else if (!regex.test(document.ExamEntry.Examination_number.value)) {
msg+="Examination number should contain exactly 4 digits";
result = false;
}

关于JavaScript 验证表单的考试编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23687166/

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