Allow Only Numeric Value in Textbox Using JavaScript

When you create a form with an input box for getting mobile number or amount then you must restrict the user to enter an only numeric value. In this article, I am going to show you how to allow the user to enter only numbers in the input box. 

To allow only numeric value in textbox using javascript or jquery we should also disable copy-paste feature so that user can not directly paste the non-numeric value to the textbox.

This tip is useful for phone numbers, IDs, Pincode and amount field validation.

So let us see how to restrict the user to enter only numbers in textbox using javascript 

The HTML

<input id="numbersOnly" onkeypress="return isNumber(event);" type="text" name="txtChar" ondrop="return false;" onpaste="return false;"> 

The JavaScript

<script type="text/javascript">
function isNumber(e)
{
var keyCode = (e.which) ? e.which : e.keyCode;

if (keyCode > 31 && (keyCode < 48 || keyCode > 57))
{
   alert("You can enter only numbers 0 to 9 ");
   return false;
}
return true;
}
</script> 

Hope you guys understood how to restrict the user to enter only numbers in textbox using JavaScript. If you liked this article don’t forget to share with others.

Leave a Comment