js驗證小數或者整數


利用正則表達式校驗是否為小數或者整數,廢話不多說直接上demo(此正則表達式無法校驗負數和數字為00開頭的數字)。

PS:(如果有不對之處,請批評指教)

<!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 === '') {
            $("#" + hintName).html("請輸入一個校驗的數字!");
            return;
        }
        if (judgeVal !== '' && notIntOrDecimal(judgeVal)) {
            $("#" + hintName).html("請輸入一個整數或小數!");
            $("#" + objName).focus();
        } else {
            $("#" + hintName).html("校驗成功!");
        }
    }
</script>

</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM