0、题目
- 如示例图中所示,在页面中实现一个输入框与按钮,要求点击验证按钮后,对输入框中内容进行格式校验,并在其下方显示校验结果
- 校验规则:
- 1.字符数为4~16位
- 2.每个英文字母、数字、英文符号长度为1
- 3.每个汉字,中文符号长度为2
1、解答过程
task29.html
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>IFE JavaScript Task 29</title> 6 <style> 7 form{ 8 margin:auto; 9 width:600px; 10 height:65px; 11 font-size: 24px; 12 } 13 input{ 14 width:300px; 15 height:30px; 16 margin:20px; 17 border-radius: 7px; 18 border:1px solid rgba(198, 202, 220, 0.35); 19 } 20 input:focus{ 21 border:1px solid rgba(181, 187, 216, 0.9); 22 border-radius: 7px; 23 outline:none; 24 25 } 26 button{ 27 border:1px solid rgba(34, 71, 255, 0.35); 28 background-color:rgba(34, 71, 255, 0.35); 29 width:150px; 30 height:40px; 31 font-size: 24px; 32 color:white; 33 letter-spacing: 10px; 34 border-radius: 7px; 35 } 36 #result{ 37 margin-left: 450px; 38 font-weight: bold; 39 color:rgba(128, 128, 128, 0.52); 40 } 41 </style> 42 </head> 43 <body> 44 <form> 45 <label for="input">名称</label> 46 <input id="input" type="text"/> 47 <button id="test">验证</button> 48 </form> 49 <div id="result">必填,长度为4~16个字符</div> 50 51 <script type="text/javascript" > 52 var input=document.getElementById('input'), 53 test=document.getElementById('test'), 54 result=document.getElementById("result"); 55 //初始状态 56 function origin(){ 57 result.innerHTML=""; 58 result.style.color="red"; 59 input.style.border="2px solid red"; 60 } 61 //点击验证按钮 62 test.addEventListener("click",function(e){ 63 origin(); 64 var length=checkLength(input.value); 65 if(length<4||length>16){ 66 result.innerHTML="字符长度为4~16个,一个汉字算两个字符!"; 67 result.style.color="red"; 68 input.style.border="2px solid red"; 69 } 70 if(!/^[a-zA-Z0-9u4e00-u9fa5]+$/.test(input.value)){ 71 result.innerHTML="只能输入中文,字母和数字哦!"; 72 result.style.color="rgba(12, 234, 81, 0.62)"; 73 input.style.border="2px solid rgba(12, 234, 81, 0.62)"; 74 } 75 if((/^[a-zA-Z0-9u4e00-u9fa5]+$/.test(input.value))&&length>=4&&length<=16){ 76 result.innerHTML="验证成功!"; 77 result.style.color="rgba(12, 234, 81, 0.62)"; 78 input.style.border="2px solid rgba(12, 234, 81, 0.62)"; 79 80 } 81 if(input.value==""){ 82 result.innerHTML="名称不能为空!"; 83 result.style.color="red"; 84 input.style.border="2px solid red"; 85 } 86 e.preventDefault(); 87 return false; 88 }); 89 //检验输入的值有多少个字符 90 function checkLength(str){ 91 var len =0,temp=0; 92 for(var j=0;j<str.length;j++){ 93 temp = 1; 94 if(/^[u2E80-u9FFF]+$/.test(str[j])){ 95 temp = 2; 96 } 97 len += temp; 98 } 99 return len; 100 } 101 </script> 102 </body> 103 </html>
2、遇到的问题
(1)阻止鼠标点击的默认事件
//停止事件冒泡
function stopPropagation(event) {
var e = event || window.event;
if (e.stopPropagation)
e.stopPropagation();
e.cancelBubble = true;
}
//停止默认事件
function preventDefault(event) {
var e = event || window.event;
if (e.preventDefault)
e.preventDefault();
e.returnValue = false;
}
element.onclick = function(e){stopPropagation(e);preventDefault(e);return false;}//兼容所有浏览器
如果是超链接即A标签的话,请将href设置为javascript:void(0);
(2)改变input框的默认样式