Monday, January 14, 2019

Allow only numbers/decimal in input box

If your requirement is to allow only numeric and decimal numbers in input box using the vanilla javascript then this post will help you in this.


Let’s get started

Step 1 – HTML Code
<input id="txtWinAmt" type="text" class="inputbox" style="width:60px; height:19px;line-height:1px" oninput="ValidateInputIsNumber(this)" />

Step 2 – javascript code
    var regEx = new RegExp(/^\d*\.?\d*$/);
    var lastValid="";
    function ValidateInputIsNumber(controlId)
    {
        if(controlId.value.length==1)
            lastValid="";

        if (regEx.test(controlId.value))
            lastValid = controlId.value;
        else
            controlId.value = lastValid;
    }

No comments: