<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <title>111</title> </head> <body> <label for="inputDemo">请输入:</label> <input name="inputDemo" id="inputDemo" type="text" value=""/> <span id="tips" style="color:red;"></span> <br/> <span id="check" style="60px;height:30px;line-height: 30px;display: inline-block;text-align: center;cursor: pointer;background-color: #eee;">检验</span> <script type="text/javascript"> window.onload = function(){ var tip = '只能输入英文和数字,且首位必须是字母,字母总数不能超过3个,总长度不能超过20!'; var tip2 = '字母总数不能超过3个'; var tip3 = '检验成功'; var btn_check = document.getElementById('check'); if(btn_check.addEventListener){ btn_check.addEventListener('click',inputDo,false); } else if(btn_check.attachEvent){ btn_check.attachEvent('onclick',inputDo); } function inputDo(){ var inputVal = document.getElementById('inputDemo').value; var reg = /^[a-zA-Z][0-9a-zA-Z]{0,19}$/; if(!inputVal.match(reg)){ document.getElementById('tips').innerText = tip; }else{ var letter = 0; var letterArr = inputVal.split(''); for(var i=0;i<letterArr.length;i++){ var asc = letterArr[i].charCodeAt(); if((asc>=97&&asc<=122)||((asc<=90&&asc>=65))){ letter++; if(letter>3){ document.getElementById('tips').innerText = '字母总数不能超过3个'; return ; } } } if(letter<=3){ document.getElementById('tips').innerText = tip3; } } } } </script> </body> </html>