js 表單驗證
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<BODY>
<form name="ff" action="as.html">
<table width="519" height="163" id="table">
<tr>
<td class="col1">電子郵箱</td>
<!--required email number 標籤名字隨便起-->
<td class="col2">
<input id="email" type="text" required="required" email="email" name="email" onblur="checkUserName(this)" />
<span id="emailW">輸入email,不能為空格式應該************</span>
</td>
</tr>
<tr>
<td>會員名</td>
<td>
<input id="username" type="text" required="required" number="number" name="username" onblur="checkUserName(this)" />
<span id="usernameW">輸入使用者名稱,不能為空格式應該************</span>
</td>
</tr>
<tr>
<td>登入密碼</td><td><input name="loginPwd" number="number" required="required" type="password" id="loginPwd" onblur="checkUserName(this)" /><span id="loginPwdW">輸入email,不能為空格式應該************</span></td>
</tr>
<tr>
<td>確認密碼</td><td><input name="repeatPwd" required="required" number="number" type="password" id="repeatPwd" onblur="checkUserName(this)" /><span id="repeatPwdW">輸入email,不能為空格式應該************</span></td>
<select id="aa"></select>
</tr>
<tr>
<td colspan="2" align="left" valign="middle">
<input type="button" value="同意以下協議,提交註冊" onclick="validate()"/>
</td>
</tr>
</table>
</form>
</BODY>
<script>
function checkUserName(obj){
var value =obj.value;
var required=obj.getAttribute("required");
var number=obj.getAttribute("number");
var email=obj.getAttribute("email");
var state=true;
if(required=='required'){//非空校驗
console.log("----------");
if(value==null||value.trim==""){
state=false;
}
}
if(email=='email'){//email校驗
var reg=/^\w+([\-_\.]?\w*)*@\w+(\.\w+){1,3}$/i;
if(!reg.test(value)){
state=false;
}
}
if(number=='number'){//數字校驗
var reg=/^[0-9]*.?[0-9]*$/;
if(reg.test(value)){
state=false;
}
}
if(state==false){
obj.style.background='red';
}else{
obj.style.background='';
}
return state;
}
function validate(){
var state=true;
var inputs=document.getElementsByTagName("input");
for(var i=0;i<inputs.length;i++){
var input=inputs[i];
if(checkUserName(input)==false){
state=false;
}
}
if(state){
document.ff.submit();
}
}
</script>
</HTML>