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

时间:2013-07-03 11:39:34

标签: javascript html validation

我目前正在开设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>

1 个答案:

答案 0 :(得分:3)

关于检查它是否为数字,您可以使用一些正则表达式: e.g。

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;