?? 9-2 判斷用戶輸入是否符合“email”地址格式.htm
字號:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=GB2312" />
<title>9-2 判斷用戶輸入是否符合“Email”地址格式</title>
<!-- 樣式表 -->
<style>
* { font-size:12px; font-family:宋體, Arial; font-weight:normal; color:#333; } /*規定了所有的字體樣式*/
</style>
<script>
function check(){
var str, result1, result2, timecost1, timecost2, timer, msg;
str = document.getElementById("txtEmail").value;
timecost1 = (new Date()).getTime();
for(var i=0; i<1000; i++)validateEmailByReg(str);
timecost1 = (new Date()).getTime() - timecost1;
timecost2 = (new Date()).getTime();
for(var i=0; i<1000; i++)validateEmail(str);
timecost2 = (new Date()).getTime() - timecost2;
msg = "輸入的Email為:“" + str + "”\r\n";
msg += "用正則測試的結果為:\t" + (validateEmailByReg(str)?"通過":"不通過") + ",運算1000遍耗時" + timecost1 + "毫秒。\r\n";
msg += "不用正則測試的結果為:\t" + (validateEmail(str)?"通過":"不通過") + ",運算1000遍耗時" + timecost2 + "毫秒。\r\n";
alert(msg);
}
function validateEmailByReg(str){
return(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(str));
}
function validateEmail(str){
var flg01, flg02, previousCharType;
flg01 = false;
flg02 = false;
for(var i=0; i<str.length; i++){
switch(charType(str.charAt(i))){
case "ascii":
if(previousCharType!="ascii")previousCharType = "ascii";
break;
case "-":
if(previousCharType!="ascii")return(false);
previousCharType = "-";
break;
case ".":
if(previousCharType!="ascii")return(false);
if(flg01)flg02=true;
previousCharType = ".";
break;
case "+":
if(previousCharType!="ascii" || flg01)return(false);
previousCharType = "+";
break;
case "@":
if(previousCharType!="ascii" || flg01)return(false);
previousCharType = "@";
flg01 = true;
break;
default:
return(false);
break;
}
}
if(!flg01 || !flg02)return(false);
return(true);
}
function charType(val){
var asciiChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
if(asciiChars.indexOf(val)!=-1){
return("ascii");
}else{
return(val);
}
}
</script>
</head>
<body style="overflow:auto;">
E-Mail:
<input id="txtEmail"><br/>
<input type="button" value="測試" onclick="check()">
</body>
</html>
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -