源代碼
點擊運行
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <p>輸入數字併點擊驗證按鈕:</p> <input id="id1" type="number" min="100" required> <button onclick="myFunction()">驗證</button> <p>如果輸入的數字小於 100 ( input 的 min 屬性), 會顯示錯誤信息。</p> <p id="demo"></p> <script> function myFunction() { var txt = ""; var inpObj = document.getElementById("id1"); if(!isNumeric(inpObj.value)) { txt = "你輸入的不是數字"; } else if (inpObj.validity.rangeUnderflow) { txt = "輸入的值太小了"; } else { txt = "輸入正確"; } document.getElementById("demo").innerHTML = txt; } // 判斷輸入是否為數字 function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); } </script> </body> </html>
運行結果