<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!--需求:表單校驗
思路:1 寫好表單框架
2 用js分別寫好每一個表單功能的校驗的方法,
3 把全部的方法封裝到一塊兒
-->
<script type="text/javascript">
//性提升代碼的複用
function check(name,id,regex,truecode,falsecode){
var flag=false;
var val =document.getElementsByName(name)[0].value;
var spannode=document.getElementById(id);
if(regex.test(val)){
spannode.innerHTML=truecode.fontcolor("green");
flag=true;
}else{
spannode.innerHTML=falsecode.fontcolor("red");
}
return flag;
}
//校驗用戶名
function checkuser(){
var useregex =new RegExp("^[a-zA-Z]{4}$");
return check("usename","userspan",useregex,"用戶名正確","用戶名錯誤");
}
//校驗密碼
function checkpsw(){
var pswregex=new RegExp("^[0-9]{4}$");
return check("psw","pswspan",pswregex,"密碼正確","密碼錯誤");
}
//校驗確認密碼
function checkpsw2(){
var psw2flag=false;
var psw2name=document.getElementsByName("psw2")[0];
var pswname=document.getElementsByName("psw")[0];
var psw2val=psw2name.value;
var pswval=pswname.value;
var psw2spannode=document.getElementById("psw2span");
if(psw2val==pswval){
psw2spannode.innerHTML="確認密碼正確".fontcolor("green");
psw2flag=true;
}else{
psw2spannode.innerHTML="確認密碼錯誤".fontcolor("red");
}
return psw2flag;
}
//校驗性別
function checksex(){
var sexflag=false;
var sexnode=document.getElementsByName("sex");
for(var x=0;x<sexnode.length;x++){
if(sexnode[x].checked){
sexflag=true;
break;
}
}
if(!sexflag){
var sexspannode=document.getElementById("sexspan");
sexspannode.innerHTML="請選擇性別".fontcolor("red");
}
return sexflag;
}
//校驗下拉菜單
function checkselect(){
var selectflag=false;
var menunode =document.getElementsByName("country")[0];
var menu_options=menunode.options;
var menuspannode=document.getElementById("menuspan");
if(menu_options[menunode.selectedIndex].value=="none"){
menuspannode.innerHTML="請選擇國家".fontcolor("red");
}else{
selectflag=true;
}
return selectflag;
}
//校驗表單
function checkform(){
if(checkuser()&&checkpsw()&&checkpsw2()&&checksex()&&checkselect()){
return true;
}else{
return false;
}
}
</script>
<form id="formid" onsubmit="return checkform()">
用戶名稱:<input type="text" name="usename" onblur="checkuser()"/><span id="userspan"></span><br/>
輸入密碼:<input type="password" name="psw" onblur="checkpsw()"/><span id="pswspan"></span><br/>
確認密碼:<input type="password" name="psw2" onblur="checkpsw2()"/><span id="psw2span"></span><br/>
選擇性別:<input type="radio" name="sex" value="nan"/>男 <input type="radio" name="sex" value="nv"/>女<span id="sexspan"></span><br/>
選擇國家:<select name="country" onchange="checkselect()">
<option value="none">選擇國家</option>
<option value="cn">中國</option>
<option value="en">英國</option>
</select><span id="menuspan"></span><br/>
<input type="submit" value="提交"/><input type="reset" value="重置"/>
<!-- <input type="button" value="提交按鈕" onclick="checkform()"/> -->
</form>
</body>
</html>javascript