使用ms ajax控件:MaskedEditExtender 可以很方便的解决~

解决方案 »

  1.   

    一个文本框里面需要输入15个字符,但最后8位必须是数字
    所以,从第8位开始必须是数字
    可以用正则表达式这样判断:
    var reg = /^\w{7}\d+$/;
    alert(reg.test(value));
      

  2.   


    <html>
    <head>
    <title>Input</title><script language="javascript" type="text/javascript">function keyPress(obj)
    {
       //字符串长度大于15是,只能输入编辑键
       if( obj.value.length >= 15 && event.ctrlKey != true)
       {
             return IsEditKey();
       }
       if( obj.value.length >= 7 )
       {
           //如果不是数字则只能输入编辑键
           if((event.keyCode < 48 || event.keyCode> 57) && 
              (event.keyCode < 96 || event.keyCode> 105) &&
              (event.ctrlKey !=true))
           {
           return IsEditKey();
           }
       }
       return true;
    }
    //判断是否编辑键
    function IsEditKey()
    {
         switch(event.keyCode)
     {
            case 8:     //Backspace Key
            case 46: //Delete Key
            case 37: //Left Key
            case 39: //Right Key
            return true;
            default: //other
            return false;
     }
    }//检查粘贴
    function CheckPaste(obj)
    {
       var resurt, re;                                // 声明变量。
       var strCopy = clipboardData.getData("TEXT");  // 从剪贴板中获取文本。
       
       //如果长度>15
       if(strCopy.length >= 15)
       {
            return false;
       }
       
       //如果总长度>7就进行检查
       if((strCopy.length + obj.value.length) > 7)
       {
            startIndex = 7-obj.value.length;
            //先将前7个字符粘贴
            obj.value = obj.value + strCopy.substr(0,startIndex);
            
            var strCheck = strCopy.substr(startIndex);  //得到要替换的字符串
            re = new RegExp("[^0-9]*","g");           // 创建正则表达式对象。
            strRepalce = strCheck.replace(re,"");       // 在字符串strCheck中去掉不是数字的字符
            //如果总长度>15,则截断字符串
            if(strRepalce.length + obj.value.length > 15)
            {
                var addLenth = 15 - strRepalce.length - obj.value.length;
                addLenth = (addLenth > 0)?addLenth : 0;
                strRepalce = strRepalce.substr(0,addLenth);
            }
            
            obj.value = obj.value + strRepalce;
       }
       else
       {
            //直接粘贴
            obj.value = obj.value + strCopy;
       }
       return false;             // 取消粘贴事件。
    }</script></head>
    <body>
    After 7 char this input box can only input number!<br/>
    <input type="text" name="txtInput" id="txtIput" onkeydown="return keyPress(this);" onPaste="return CheckPaste(this);"/>
    </body>
    </html>