簡體   English   中英

我希望使我的代碼驗證一個字段,以確保它是四位數。 我怎樣才能做到這一點?

[英]I wish to make my code validate a field to make sure it is a number of four digits. How can I do this?

我目前正在上一門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>

關於檢查是否為數字,可以使用一些正則表達式:例如

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插入的方法,即“ masked input”

編輯:var reg = /\\d{4}/ig;更改行var reg = /\\d{4}/ig; var reg = /^\\d{4}$/ig;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM