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>checkNumbertitle>
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>

 

你可能感兴趣的:(js验证小数或者整数)