Numeric only validation in javascript
So for restricting the user from typing alphabets in your input box we will use onkeypress event of the input box and then use js for restricting invalid characters.
Below is a code in HTML and JavaScript to number validate a text field.
<form> <div class="form-group row"> <label for="inputPassword" class="col-sm-2 col-form-label">Enter Amount</label> <div class="col-sm-10"> <input type="text" class="form-control" id="inputNumber" placeholder="Enter Amount" value="" name="inputNumber" onkeypress="return isNumber(event)" /> </div> </div> </form>
Here is how to validate the input only to accept numbers this will only take numeric values like "112233" . Here, we are using event keycodes to know which character are invalid and which are valid ones.
<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>
You can use this Complete code of HTML form and numeric function for applying the validation in js.
<form> <div class="form-group row"> <label for="inputPassword" class="col-sm-2 col-form-label">Enter Amount</label> <div class="col-sm-10"> <input type="text" class="form-control" id="inputNumber" placeholder="Enter Amount" value="" name="inputNumber" onkeypress="return isNumber(event)" /> </div> </div> </form> <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>
So, now you can run the application and you will see you are able to enter only numeric characters now. So this is how we can implement numeric only validation in javascript.