gpt4 book ai didi

javascript - 我希望让我的代码验证一个字段以确保它是四位数字。我怎样才能做到这一点?

转载 作者:行者123 更新时间:2023-11-28 20:25:47 24 4
gpt4 key购买 nike

我目前正在学习 GCSE 类(class),只要我在调查中引用 IT 资源,我就可以向它们寻求帮助。我希望使用以下代码验证考试号输入字段中是否有四位数字。我可以接受简单的验证,但这对我来说是另一个步骤。

    <head>
<title>Exam entry</title>
<script language="javascript" type="text/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.examnumber.value=="") {
msg+="You must enter your Examination Number \n";
document.ExamEntry.examnumber.focus();
document.getElementById('examnumber').style.color="red";
result = false;
}

var checked = null;
var inputs = document.getElementsByName('examtype');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
document.getElementById('examtype').style.color="red";
}
}
if(checked==null)
{
msg+="Please choose an option";
result = false;
}
else{
confirm("You have chosen "+checked.value+" is this the correct course?");
}

if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="examnumber">Examination Number</td>
<td><input type="text" name="examnumber" /></td>
</tr>
<tr>
<td><input type="radio" id="examtype" name="examtype" value="GCSE" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" value="A2" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" value="AS"/> : AS<br />
</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>
</body>

最佳答案

关于检查它是否是数字,您可以使用一些正则表达式:例如

var reg = /^\d{4}$/ig;
var regExRes = reg.exec(document.ExamEntry.examnumber.value);
if (document.ExamEntry.examnumber.value == "" || (regExRes == null || regExRes.length == 0)) {

msg += "You must enter your Examination Number \n";
document.ExamEntry.examnumber.focus();
document.getElementById('examnumber').style.color = "red";
result = false;
}

为了避免输入数字以外的任何内容,我建议您使用名为 masked input 的 jquery 插件之类的东西。

编辑:该行从 var reg =/\d{4}/ig; 更改为 var reg =/^\d{4}$/ig;

关于javascript - 我希望让我的代码验证一个字段以确保它是四位数字。我怎样才能做到这一点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17446959/

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