1 <html> 2 <head> 3 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 4 <title>即時驗證</title> 5 <style> 6 #error{ 7 color:red; 8 font-weight:bold; 9 } 10 </style> 11 <script type="text/javascript"> 12 // Firefox, Google Chrome, Opera, Safari, Internet Explorer from version 9 13 function OnInput (event) { 14 //alert ("The new content: " + event.target.value); 15 var value = event.target.value; 16 checkusername(value); 17 } 18 // Internet Explorer 19 function OnPropChanged (event) { 20 console.info(event) 21 if (event.propertyName.toLowerCase () == "value") { 22 var value = event.srcElement.value; 23 checkusername(value); 24 } 25 } 26 //驗證用戶名方法(只能是數字字母和中文,不能包括特殊字符) 27 function checkusername(value){ 28 var regex = /^[0-9a-zA-Z\u4e00-\u9fa5]*$/; 29 if(regex.test(value) == true){ 30 //格式正確 31 document.getElementById("error").innerHTML=""; 32 }else{ 33 //格式錯誤 34 document.getElementById("error").innerHTML="用戶名格式錯誤,用戶名由數字、字母、中文組成,不能包含特殊字符"; 35 } 36 } 37 </script> 38 </head> 39 <body> 40 請輸入用戶名: 41 <input name="username" type="text" oninput="OnInput (event)" onpropertychange="OnPropChanged (event)" placeholder="數字、字母、漢字" /><label id="error"></label> 42 </body> 43 </html>