Set input field number only set maximum input size using javascript

Want to set number only on input field of a form? and also restrict the maximum input length. The below given example will help you to achive this.

Here is a example of it.

First we will set number only for that input field.

<input type="text" onkeydown="onlynumber(event)" >



function onlynumber(event) {

    var regex = new RegExp("^[0-9\t\b]+$");

	var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);

	if (!regex.test(key)) {


   	return false;



And then if you also want to restrict the maximum length of input add this inline function 

onkeypress="return isNumberKey(event)"


<input type="text" onkeydown="onlynumber(event)" onkeypress="return isNumberKey(event)" maxlength="10">

and don't forget to add maxlength, and this function will work only on text type input it will not work on type="number".


Thank you.

Other posts