Allow 18 digit number with two decimals in jQuery

Last Reply 3 months ago By dharmendr

Posted 3 months ago

I have a textbox field where i need to allow 18 or less than 18 digits and not more than 2 decimals (it may be 1 or 2 but not more than two).

Totally 18 digits before decimal if it exceeds 18 digits i need to add a dot and allow only two digits after decimal.

i.e 123456789123456789.98

or 12345678.44

or 1234567891234.22

How can i do this

Posted 3 months ago Modified on 3 months ago

Hi kavithav,

Refer below code.

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#txtValue').on('keyup', function () {
                if ($(this).val().split('.').length == 1) {
                    $('span').hide();
                    if ($(this).val().length == 18) {
                        $(this).val($(this).val() + ".");
                        $('span').show();
                    }
                } else {
                    if ($(this).val().split('.')[1].length == 0 || $(this).val().split('.')[1].length > 2) {
                        $('span').show();
                    } else {
                        $('span').hide();
                    }
                }
            });
        });
    </script>
</head>
<body>
    <input name="txtValue" type="text" id="txtValue" style="width: 200px" />
    <span style="display: none; color: Red;">Invalid</span>
</body>
</html>

Demo