<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>表单验证</title> <style> .names{ width:358px; height:42px; margin-left:38px; -webkit-border-radius:5px; -moz-border-radius:5px; border-radius:5px; } .btn{ width:78px; height:42px; margin-left:15px; background: rgb(46,122,184); color: #fff; font-size:18px; font-weight: bold; outline: none; border:0; border-radius: 5px; } .pro{ position: relative; left:78px; font-size:16px; color: #ccc; } </style> </head> <body> <form action="#"> <label for="t1" class="tit">名称</label> <input type="text" id="t1" class="names" name="names"> <button type="submit" class="btn" id="btn">验证</button> <p> <span class="pro" id="pro"></span> </p> </form> </body> <script> var $=function(id){ return document.getElementById(id); }; addEventHandler($("btn"),"click", judge); function judge(){ $("pro").innerHTML=""; var value=$("t1").value; console.log(value); if(!value){ $("pro").innerHTML ="不能为空"; }else if(countLength(value)<4 &&countLength(value)>16){ $("pro").innerHTML ="您输入的字符超过16个"; }else{ $("pro").innerHTML ="输入正确"; } } function countLength(str){ var count =0; for(var i=0;i<str.length;i++){ var code = str[i].charCodeAt(); //检查每个字符是否为除中文外的字母 if(code>=0&&code<=128){ count++; }else{ count +=2; } } return count; } function addEventHandler(element, event, listener) { //当前元素、事件、函数 if (element.addEventListener) { element.addEventListener(event, listener, false); } else if (element.attachEvent) { element.attachEvent("on" + event, listener); } else { element['on' + event] = listener; } } </script> </html> <!-- 字符数为4-16为 每个英文字母、数字、英文符号长度为1 每个汉字,中文符号长度为2-->
山_3
Developer_Zuck
相关分类