Javascript验证-如何检查表单中输入的数字是否在一定范围内?
我有这部分html代码:Javascript验证-如何检查表单中输入的数字是否在一定范围内?,javascript,html,validation,Javascript,Html,Validation,我有这部分html代码: <tr> <td id="examnumber">Examination number</td> </tr> <tr> <td><input type="text" name="examnumber"/></td> </tr> 考试号码 我需要输入的数字长度为4位,范围在0000-9999之间。我尝试使用以下javascript代码对其进行验
<tr>
<td id="examnumber">Examination number</td>
</tr>
<tr>
<td><input type="text" name="examnumber"/></td>
</tr>
考试号码
我需要输入的数字长度为4位,范围在0000-9999之间。我尝试使用以下javascript代码对其进行验证:
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.examnumber.value=="") {
msg+="You must enter your examination number. \n";
document.ExamEntry.examnumber.focus();
document.getElementById('examnumber').style.color="red";
} else if ((document.ExamEntry.examnumber.value.length < 0) || (document.ExamEntry.examnumber.value.length > 9999)) {
msg+= "The examination number is not within the range 0000-9999.\n";
result = false
}
if (document.ExamEntry.examnumber.value.length!=4) {
msg+="Your examination number must be 4 digits long. \n";
document.ExamEntry.examnumber.focus();
document.getElementById('examnumber').style.color="red";
result = false;
}
函数validateForm(){
var结果=真;
var msg=“”;
if(document.ExamEntry.examnumber.value==“”){
msg+=“您必须输入您的考试编号。\n”;
document.ExamEntry.examnumber.focus();
document.getElementById('examnumber').style.color=“红色”;
}else if((document.ExamEntry.examnumber.value.length<0)| |(document.ExamEntry.examnumber.value.length>9999)){
msg+=“检查编号不在0000-9999范围内。\n”;
结果=错误
}
if(document.ExamEntry.examnumber.value.length!=4){
msg+=“您的考试编号必须是4位数字。\n”;
document.ExamEntry.examnumber.focus();
document.getElementById('examnumber').style.color=“红色”;
结果=假;
}
但是,当我通过输入-900或3.45测试代码时,它不会出现错误消息,并表示信息输入正确。如果有人能帮助我修复此错误,我将不胜感激
/^\d{4}$/.test(document.ExamEntry.examnumber.value)
如果这个Regexp正好包含4位数字(0-9),它将返回true。这里的主要问题是字段名为
examnumber
,您试图通过表单名(大概是ExamEntry
)来获取它。以这种方式获取对字段的引用(document.form\u name.field\u name
)过时了,只在Internet Explorer上真正工作过
一种更通用的方法是使用
您在这行中使用的是:
document.getElementById('examnumber').style.color="red";
但是examnumber
是字段名,而不是Id。您还应该向字段添加Id:
<td><input type="text" name="examnumber" id="examnumberfield"/></td>
(我建议对值进行简单的正则表达式测试既可以验证值的长度,也可以验证值的数字状态-无需单独测试。)“examnumber”也是的id。
var examnumberlabel = document.getElementById("examnumber");
var examnumberfield = document.getElementById("examnumberfield");
if (examnumberfield.value=="") {
msg+="You must enter your examination number. \n";
examnumberfield.focus();
examnumberlabel .style.color="red";
//.. etc