注:表單在提交的時候回觸發submit()事件,如果該事件的返回值爲false不允許被提交
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
//檢查用戶名
function checkName(){
var inputNode = document.getElementById("userName");
var spanNode = document.getElementById("userId");
//獲取輸入框的內容
var content = inputNode.value;
//用戶名的規則: 六位的英文與數字組成。數字不能開頭
var reg = /^[a-z][a-z0-9]{5}$/i;
if(reg.test(content)){
//符合規則
spanNode.innerHTML = "正確".fontcolor("green");
return true;
}else{
//不符合規則
spanNode.innerHTML = "錯誤".fontcolor("red");
return false;
}
}
//檢查郵箱
function checkEmail(){
var email = document.getElementById("email").value;
var spanNode = document.getElementById("emailspan");
//編寫郵箱的正則 [email protected] [email protected] [email protected]
var reg = /^[a-z0-9]\w+@[a-z0-9]+(\.[a-z]{2,3}){1,2}$/i;
if(reg.test(email)){
//符合規則
spanNode.innerHTML = "正確".fontcolor("green");
return true;
}else{
//不符合規則
spanNode.innerHTML = "錯誤".fontcolor("red");
return false;
}
}
function checkAll(){
var userName = checkName();
var email = checkEmail();
if(userName&&email){
return true;
}else{
return false;
}
}
/*
表單提交的時候是會觸發onsubmit事件的,如果onsubmit事件的方法返回是true,那麼該表單允許提交,如果返回的是false,該表單不允許提交。
*/
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>正則表達式</title>
</head>
<body>
<form action="success.html" method="get" οnsubmit="return checkAll()" > <!--如果表單提交時候觸發的方法返回是false,那麼該表單不允許提交,如果返回的是true允許提交 -->
<table border="1px" width="50%" align="center" cellspacing="0px" cellpadding="3px">
<tr>
<td width="25%">姓名:</td>
<td>
<input type="text" name="userName" id="userName" οnblur="checkName()"/>
<span id="userId"></span>
</td>
</tr>
<tr>
<td >密碼:</td><td>
<input type="password" name="pwd" id="pwd" οnblur="checkPass()"/>
<span id="passId"></span>
</td>
</tr>
<tr>
<td>確認密碼:</td><td>
<input type="password" name="ensurepwd" id="ensurepwd" οnblur="ensurepass()" /> <span id="ensure"></span>
</td>
</tr>
<tr>
<td>郵箱</td><td>
<input type="text" name="email" id="email" οnblur="checkEmail()"/>
<span id="emailspan"></span>
</td>
</tr>
<tr>
<td>性別</td><td>
<input type="radio" checked="ture" name="gender" id="male" value="male"/>
男
<input type="radio" name="gender" value="female"/>
女</td>
</tr>
<tr>
<td>愛好:</td><td>
<input type="checkbox" name="like" />
eat
<input type="checkbox" name="like" />
sleep
<input type="checkbox" name="like"/>
play
<span id="hobbySpan"></span>
</td>
</tr>
<tr>
<td>城市</td><td>
<select name="city" id="city">
<option value=""> 請選擇</option>
<option value="bj"> 北京 </option>
<option value="gz"> 廣州 </option>
<option value="sh"> 上海 </option>
</select>
</td>
</tr>
<tr>
<td>自我介紹</td><td> <textarea cols="15" rows="5" name="myInfo" id="myInfo"></textarea></td>
</tr>
<tr align="center">
<td colspan="2"><!--提交按鈕-->
<input type="submit"/>
</td>
</tr>
</table>
</form>
</body>
</html>