JavaScript input框输入实时校验
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>