Validation to accept numbers between specific range in TextBox using JavaScript

Last Reply one month ago By pandeyism

Posted one month ago

Below is my javascript code which is used to validate the percentage entered in textboxes.But it should accept from 35 to 99 only if user enters a number below 35 or above 99 it should not accept how can i do this

it should accept only two digit numbers from 35 to 99 without spaces.

<asp:TextBox ID="txtClassXPercentage" runat="server" CssClass="textboxstylesmall2" onblur="validatepercent(this);"></asp:TextBox>
 function validatepercent(inputtxt) {
        var percent = inputtxt.value;
        document.getElementById('lblMessage').innerHTML = "";
        var val = percent
        if (val == "" || val == undefined) {
            return true;
        }
        else {
            var reg = /(^100(\.0{1,2})?$)|(^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$)/i;
            var result = reg.exec(val);
            if (!result) {
                document.getElementById('lblMessage').innerHTML = "Enter a valid percentage";
                inputtxt.value = "";
                inputtxt.focus();
                return false;
            }
            else {
                document.getElementById('lblMessage').innerHTML = "";
                return true;
            }
        }
    }

 

Posted one month ago

Hi nalinid93,

Please take reference the below code and correct your code.

HTML

<input name="txtClassXPercentage" type="text" id="txtClassXPercentage" class="textboxstylesmall2"
    onblur="validatepercent(this);" />
<span id="lblMessage"></span>
<script type="text/javascript">
    function validatepercent(inputtxt) {
        var percent = inputtxt.value;
        document.getElementById('lblMessage').innerHTML = "";
        if (percent == "" || percent == undefined) {
            return true;
        }
        else {
            if (percent < 35 || percent > 99) {
                document.getElementById('lblMessage').innerHTML = "Enter a valid percentage between 35 and 99.";
                inputtxt.value = "";
                inputtxt.focus();
                return false;
            }
            else if (percent.length != 2) {
                document.getElementById('lblMessage').innerHTML = "Enter Two digit without space.";
            }
            else {
                return true;
            }
        }
    }
</script>

Demo