js验证小数或者数字
程序员文章站
2023-11-21 22:56:04
利用正则表达式匹配是否为数字,直接上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>
上一篇: PHP的SPL标准库