gpt4 book ai didi

javascript - 我如何使用 javascript 验证 html 中的文本字段?

转载 作者:行者123 更新时间:2023-11-28 07:32:57 25 4
gpt4 key购买 nike

我有一个文本字段供用户输入 4 位数长的考试编号。我如何验证文本字段以确保输入的数字恰好是 4 位数字(包括前导 0)。

到目前为止,我已经对其进行了验证,因此它不会留空。这是我的 JavaScript:

function validateForm() 
{
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;
}



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


if(msg=="")
{

return result;
}
{
alert(msg)
return result;
}
}

这是我的 html:

<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>

</tr>
<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>

<tr>
<td id="ExamNo">Examination number</td>
<td><input type="text" name="ExamNo"/></td>
</tr>


<tr>
<td><input type="submit" name="Submit" value="Submit" onClick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>

最佳答案

/^\d\d\d\d$/.test(document.ExamEntry.ExamNo.value)

它返回一个 bool 值,检查 ExamNo 是否与正则表达式(4 位字符串)匹配。

完整示例:

if (!/^\d\d\d\d$/.test(document.ExamEntry.ExamNo.value))
{
msg+="Examination number should be 4-digit number. \n";
document.ExamEntry.ExamNo.focus();
document.getElementById('ExamNo').style.color="red";
result = false;
}

关于javascript - 我如何使用 javascript 验证 html 中的文本字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28918093/

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