怎么判读输入的 必须 而且只能是四个数字 不懂正则  请教大家

解决方案 »

  1.   


    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题文档</title>
    <style>
    *{margin:0; padding:0;}
    </style>
    </head>
    <body>
    <input type="text" id="t" maxlength="4" />
        <input type="button" id="btn" value="click me" />
        <script>
         document.getElementById('btn').onclick = function(){
    var value = document.getElementById('t').value;
    if(!isNaN(+value) && value.length == 4){
    alert('是数字')
    }else{
    alert('不是数字或者少于4位')
    }
    };
        </script>
    </body>
    </html>
      

  2.   

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题文档</title>
    <script type="text/javascript">
    window.onload = function() {
    document.getElementsByTagName('form')[0].onsubmit = function() {
    var num = document.getElementById('num').value;
    if (!/^[0-9]{4}$/.test(num)) {
    alert('必须输入4位数字!');
    return false;
    }
    if (!/^[1-9]{1}[0-9]{3}$/.test(num)) {
    alert('必须输入4位正整数!');
    return false;
    }
    return true;
    }
    }
    </script>
    </head><body>
    <form>
    <input type="text" id="num" name="num" />
        <input type="submit" />
    </form>
    </body>
    </html>