源代碼
點擊運行
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <p>輸入數字併點擊驗證按鈕:</p> <input id="id1" type="number" min="100" max="300" required> <button onclick="myFunction()">驗證</button> <p>如果輸入的數字小於 100 或大於300,會提示錯誤信息。</p> <p id="demo"></p> <script> function myFunction() { var inpObj = document.getElementById("id1"); if (inpObj.checkValidity() == false) { document.getElementById("demo").innerHTML = inpObj.validationMessage; } else { document.getElementById("demo").innerHTML = "輸入正確"; } } </script> </body> </html>
運行結果