Prevent (Restrict) first character zero in TextBox in JavaScript

mahesh213
 
on Aug 30, 2020 11:42 PM
Sample_120744.zip
2652 Views

Hi,

I have one text box

currently my requirement is that onkeypress of textbox element don't allow zero as 1st character

could you please help me

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Aug 31, 2020 02:07 AM
on Aug 31, 2020 04:09 AM

Hi mahesh213,

Refer below sample.

HTML

<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script type="text/javascript">
        function RestrictFirstZero(e) {
            if (e.srcElement.value.length == 0 && e.which == 48) {
                e.preventDefault();
                return false;
            }
        };

        function PreventFirstZero(event) {
            if (event.srcElement.value.charAt(0) == '0') {
                event.srcElement.value = event.srcElement.value.slice(1);
            }
        };
    </script>
</head>
<body>
    <input type="text" id="txtNumber" onkeypress="RestrictFirstZero(event)" />
    <hr />
    <input onkeyup="PreventFirstZero(event)" />
</body>
</html>

Demo