21.6 C
New York

javascript allow only numbers

Published:

Here are three (3) methods javascript allow only numbers in a form field

  1. Using Keypress event
    Allow only numbers to be typed in a textbox
<input type="text" onkeypress="return isNumber(event)" />
<script>
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>

method 1 works but if you copy and paste non numeric characters in the input field it will accept and didn’t decline the input but sometimes if you want to be strict with the input you may need to wipe out the non numeric when attempt is made at all.

  1. Using replace preg_match characters
    let’s take for example we are programming a payment portal where the 16 digit card payment numbers and cvv were to be validated to make sure that only numeric values are accepted from the client.
<label for="pcn">payment card number</label>
<input type="text" name="pcn" oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/(\..*)\./g, '$1');" maxlength="17" />
<label for="ccv">ccv</label>
<input type="text" name="pcn" oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/(\..*)\./g, '$1');" maxlength="4" />

applying the above code example in javascript function it looks like this

function validate(field) {
   let val = field.value;
   let data = val.replace(/[^0-9]/g, "");
   field.value = data;
}
</script>
<label for="withdrawalpin">Atm pin</label>
<input name="withdrawalpin" type="text" oninput="validate(this)">
  1. oninput event was used instead of keypress / keyup / keydown events
  2. maxlength is used to maintain / check the length of the input
  3. replace preg_match was used to check if the input are numeric if not replace it with null data

assuming we don’t need to make the process you can apply pattern attribute but the bad news is that the below pattern attribute for validating if input field data is numeric no longer work though we don’t know if it have worked before but as of the time of this publication it no longer work across all browser.

<label for="mark">Enter score:</label>
<input type="text" name="mark" pattern="[0-9]+">

finally we strongly advice against using pattern and keypress event instead use on oninput event and replace preg_match to strictly make javascript allow only numbers are input in a certain field even though copy and paste is used it will still restrict that only numbers are required.

  1. preventing copy and paste while validating field data input is numeric in javascript
<label for="accountno">Bank Account No:</label>
 <input type="text" name="accountno" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" />
    <span id="error" style="color: #FF0; display: none">* characters allowed (0 - 9)</span>
    <script type="text/javascript">
        var specialKeys = new Array();
        specialKeys.push(8); //Backspace
        function IsNumeric(e) {
            var keyCode = e.which ? e.which : e.keyCode
            var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
            document.getElementById("error").style.display = ret ? "none" : "inline";
            return ret;
        }
    </script>

Notice that the 3rd method javascript events such as ondrop and onpaste are applied to prevent input made by copy and paste.

Godwin
Godwinhttps://shopinson.com
Owner and founder of shopinson.com. He is a passionate programmer with enthusiasm in daily discovering of solving logic with new block of codes. He loves creating contents and blogging his new discoveries on programming language and related peripherals.

Related articles

spot_img

Recent articles

spot_img