网上看到过很多javascript验证数字输入的方法, 自己也写了个算是总结吧. 如有算法和逻辑上的问题, 欢迎大家拍砖啊. IE6.0下测试通过.
转载请注明出自: http://blog.csdn.net/pisces_fri/
<SCRIPT language="javascript" type="text/javascript"> /** * @author: pisces.fri */
// ============================================================================= // validationNumber methods
/** * Validate the input text as a number * * @param object ID of the input control object * @param string Number type ('int', 'u_int', 'float' or 'u_float') * @param number Max number allowed to input * @param object ID of the error message control object * * @return null */ function validationNumber(hndID, numType, maxNum, hndMsgID) { var keyCode = window.event.keyCode; var ch = String.fromCharCode(keyCode); var value = ''; var retCode = 0; var oNumVerify=null;
//屏蔽回车键 if (keyCode==13) { window.event.keyCode = 0; return null; }
if (hndID != undefined) { value += hndID.value+ch; } else { window.event.keyCode = keyCode; return null; }
oNumVerify = new isNumeric(value); if (oNumVerify.isNumber) { numType = numType.toString().toLowerCase(); switch(numType) { case 'u_int': //正整数 if ((oNumVerify.isMinus==false) && (oNumVerify.isDecimal==false)) { retCode = keyCode; } break; case 'u_float': //正实数 if (oNumVerify.isMinus==false) { retCode = keyCode; } break; case 'int': //整数 if (oNumVerify.isDecimal==false) { retCode = keyCode; } break; case 'float': //实数 retCode = keyCode; break; default: retCode = 0; }
//判断输入的数字是否超过设置的最大值 if ((maxNum!=undefined) && (maxNum.constructor==Number) && (oNumVerify.value > maxNum)) { retCode = 0; if (hndMsgID != undefined) { hndMsgID.innerHTML = '<SPAN style="color:#EE3333">值不能大于'+maxNum+'</SPAN>'; } } }
oNumVerify = null; window.event.keyCode = retCode; return null; }
function isNumeric(verifyNum) { var re = /^([-]{0,1})([0-9]*)([/.]{0,1})([0-9]*)$/g; this.isNumber = false; this.isMinus = false; this.isDecimal = false; this.value = verifyNum;
verifyNum = verifyNum.toString();
if (re.test(verifyNum)) { this.isNumber = true; re.exec(verifyNum);
//判断 '-' 符号 if (RegExp.$1=='-') { this.isMinus = true; }
//判断 '.' 符号 if (RegExp.$3=='.') { this.isDecimal = true; verifyNum += '0'; }
try { this.value = parseFloat(verifyNum); } catch(e) { this.value = 0; } }
return; } </SCRIPT> 使用方法:<br/> <INPUT type="text" name="txtYear" id="txt_Year" size="4" οnkeypress="javascript:validationNumber(this, 'float', 2006, txtYearMsg);" style="text-align:right;ime-mode:disabled;" maxlength="4"/>年 <SPAN id="txtYearMsg"></SPAN>
IE6.0下测试通过.