Check if TextBox value starts with specific number using JavaScript in ASP.Net

Ikramshams
 
on Jul 30, 2021 10:56 PM
Sample_104891.zip
690 Views

I have ASP.Net TextBox. I want validation on its keypress that the Textbox should accept only numeric and the number should starts with 05.

In my javascript function it is accepting numeric only. What I will make changes in that function that the number should start only with 05 using Javascript.

<script type="text/javascript">
    function isNumber(evt) {
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }
        return true;
    }
</script>

 

<asp:TextBox ID="txtMobileNo" runat="server" onkeypress="return isNumber(event)" MaxLength="10" ></asp:TextBox>

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jul 31, 2021 01:42 AM

Hi Ikramshams,

Refer below code.

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <input type="text" id="txtMobileNo" maxlength="10"
        onkeypress="return isNumber(event)" oninput="isStartWith(event)" />
    <script type="text/javascript">
        function isNumber(evt) {
            evt = (evt) ? evt : window.event;
            var charCode = (evt.which) ? evt.which : evt.keyCode;
            if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                return false;
            }
            return true;
        }

        function isStartWith(evt) {
            var value = evt.target.value;
            if (value.charAt(0) != '0') {
                evt.target.value = '';
            }
            else if (value.charAt(1) != '5') {
                evt.target.value = '0';
            }
        }
    </script>
</body>
</html>

Demo