網路設定類表單常需要驗證四種位址格式。以下用一個完整範例說明如何在提交前逐一檢查,並把焦點移回有問題的欄位。
<script language="javascript">
<!--
function checkdata() {
// IP / 子網遮罩 / 閘道共用的 IPv4 格式
var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){3}$/;
if (myform.ip.value == "") {
alert("IP 不能為空"); myform.focus(); return false;
}
if (!myform.ip.value.match(reg)) {
alert("IP 不合法"); myform.focus(); return false;
}
if (myform.zwym.value == "") {
alert("子網遮罩不能為空"); myform.focus(); return false;
}
if (!myform.zwym.value.match(reg)) {
alert("子網遮罩不合法"); myform.focus(); return false;
}
if (myform.gateway.value == "") {
alert("閘道不能為空"); myform.focus(); return false;
}
if (!myform.gateway.value.match(reg)) {
alert("閘道不合法"); myform.focus(); return false;
}
if (myform.mac.value == "") {
alert("MAC 不能為空"); myform.focus(); return false;
}
if (!myform.mac.value.match(/^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}$/)) {
alert("MAC 不合法"); myform.focus(); return false;
}
return true;
}
//-->
</script>
表單本體:
<form method="post" name="myform" onSubmit="return checkdata();">
<table width="708" height="253" border="1" id="table1">
<tr>
<td width="186"><div align="center">IP 地址:</div></td>
<td width="506">
<input type="text" name="ip" size="15" maxlength="15" />
<font color="#FF0000">*</font>不能為空,必須填寫
</td>
</tr>
<tr>
<td width="186"><div align="center">子網遮罩:</div></td>
<td width="506">
<input type="text" name="zwym" size="15" maxlength="15" />
<font color="#FF0000">*</font>不能為空,必須填寫
</td>
</tr>
<tr>
<td width="186"><div align="center">閘 關:</div></td>
<td width="506">
<input type="text" name="gateway" size="15" maxlength="15" />
<font color="#FF0000">*</font>不能為空,必須填寫
</td>
</tr>
<tr>
<td width="186"><div align="center">MAC 地址:</div></td>
<td width="506">
<input type="text" name="mac" size="15" maxlength="15" />
<font color="#FF0000">*</font>不能為空,必須填寫
</td>
</tr>
<tr>
<td height="47" colspan="2" align="center">
<input type="submit" value="提交" />
<input type="reset" value="重置" />
</td>
</tr>
</table>
</form>
幾點補充:IPv4 的正則把每一段限制在 0–255,避免出現 999 這類不可能的值;MAC 位址則改用 xx:xx:xx:xx:xx:xx 的十六進位格式,與 IP 共用同一個正則是原範例的疏漏。若你的表單使用 myform 這種 IE 專屬的name 取元素方式,在標準瀏覽器中需改用 document.forms['myform'] 或 getElementById。