How to set an input box that will only accept numeric values?

Edited by pritaeas: Please do not use ALL CAPS text/title.

4 Years
Discussion Span
Last Post by JorgeM

Use clients side and server side techniques.

First, you can use HTML5 input type number to restrict only number entries:

 <input type="number" name="txtBox1" />

This will work only in browsers that support this HTML5 input type.

Next is JavaScript...

 function isNumber(e) {
 var char = (e.which) ? e.which : event.keyCode
 if (char > 31 && (char < 48 || char > 57))
    return false;
 return true;

 <input type="text" name="number" onkeypress="return isNumber(event)">

Server side--PHP

 if (!is_numeric($num)) {
     echo 'Input is not numeric';

Edited by JorgeM


by the way, in addtion, in the input box i need to input the year. a year is only 4 digits but i can type more than 4 digits. is there anyway to limit the number of digits or characters to be entered to 4?

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.