利用isNaN()判斷數字
isNaN() 函數用於檢查其參數是否是非數字值。
說明:
isNaN() 函數可用於判斷其參數是否是 NaN,該值表示一個非法的數字(比如被 0 除後得到的結果)。
如果把 NaN 與任何值(包括其自身)相比得到的結果均是 false,所以要判斷某個值是否是 NaN,不能使用 == 或 === 運算子。正因為如此,isNaN() 函數是必需的。
測試:
| 代碼如下 |
複製代碼 |
document.write(isNaN(123)); // false document.write(isNaN(-1.23)); // false document.write(isNaN(5-2)); // false document.write(isNaN(0)); // false document.write(isNaN("Hello")); // true document.write(isNaN("2005/12/12")); // true document.write(isNaN("6/2")); // true document.write(isNaN("3")); // false |
例
算參數,如果值為 NaN(非數字),則返回 true。此函數可用於檢查一個數學運算式是否成功地計算為一個數字。
| 代碼如下 |
複製代碼 |
if(isNaN(document.login.imgcode.value)){ alert('驗證碼必須是數字!') document.login.imgcode.focus(); return false; } if(!isNum(document.getElementById("prjSum").value)){ alert("造價只能是數字"); document.getElementById("prjSum").focus(); return false; } |
利用Regex為檢查數字
不錯的一個用正則檢測輸入的字元是否為數位代碼,也是一種並不常見的寫法
| 代碼如下 |
複製代碼 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB2312" /> <title>Untitled Document</title> </head> <body> <input type="text" id="myInput" value="" /> <input type="button" value="確定" id="myButton" /> </body> </html> <script language="JavaScript" type="text/javascript"> function $(obj){ return document.getElementByIdx(obj); } function checkIsInteger(str) { //如果為空白,則通過校正 if(str == "") return true; if(/^(-?)(d+)$/.test(str)) return true; else return false; } String.prototype.trim = function() { return this.replace(/(^[s]*)|([s]*$)/g, ""); } $("myButton").onclick=function(){ if(checkIsInteger($("myInput").value.trim())){ alert("成功"); }else{ alert("只能是數字"); } } </script> |