0

我目前正在上一门 GCSE 课程,只要我在调查中引用它们,我就可以向 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>
4

1 回答 1

3

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

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;
}

为避免输入数字以外的任何内容,我建议您使用类似 jquery pluging 之类的东西,称为masked input

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

于 2013-07-03T11:50:52.070 回答