利用正則表達式匹配是否為數字,直接上demo ...
利用正則表達式匹配是否為數字,直接上demo
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>checkNumber</title> </head> <body style="background-color: aliceblue;"> <div id="main" style="margin: 0 auto; text-align: center; "> <form method="POST" action="" style="width: 50% ; height: 50%; text-align: center;margin: 0 auto; padding-top: 20%;"> <label>請輸入判斷的數字:</label><input type="text" id="amount" name="amount" onblur="checkAmount('amount','hint')" /><br /> <p><span name="hint" id="hint" style="color: red"></span></p> </form> </div> </body> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script type="text/javascript"> $(function () { //設置div高度 $("#main").css("height", $(document).height); $("#main").css("width", $(document).width); }); function notIntOrDecimal(text) { //校驗(小數/數字)正則表達式 let pattern = /^[0-9]+([.]{1}[0-9]+){0,1}$/; if (pattern.test(text)) { return false; } else { return true; } } function checkAmount(objName, hintName) { let judgeVal = $("#" + objName).val(); if (judgeVal !== '' && notIntOrDecimal(judgeVal)) { $("#" + hintName).html("請輸入一個整數或小數!"); $("#" + objName).focus(); } else { $("#" + hintName).html("校驗成功!"); } } </script> </html>