Validate numeric input field using JavaScript

Mohammed Imtiyaz Jun 1, 2014

This example will explain you how to validate input integers using JavaScript. Though they are many ways to validate input data, we will use here one of the efficient way to achieve this using JavaScript.

Live Demo

HTML Controls

<!DOCTYPE html>
<html>
   <body>
	<label for="txtExample1">Example 1:</label>
      	<input type="text" id="txtExample1" onKeyPress="return onlyNumbers();" />
        
        <label for="txtExample2">Example 2:</label>
      	<input type="text" id="txtExample2" onKeyUp="isNumeric(this);" />
   </body>
</html>

JavaScript Function (Example 1)

function onlyNumbers(evt) {
    var e = event || evt; // for trans-browser compatibility
    var charCode = e.which || e.keyCode;
    if (charCode & #x3E; 31 & #x26; & #x26;
        (charCode & #x3C; 48 || charCode & #x3E; 57))
        return false;
    return true;
}

JavaScript Function (Example 2)

function isNumeric(x) {
    var s_len = x.value.length;
    var s_charcode = 0;
    for (var s_i = 0; s_i < s_len; s_i++) {
        s_charcode = x.value.charCodeAt(s_i);
        if (!((s_charcode >= 48 && s_charcode <= 57))) {
            alert("Only Numeric Values Allowed");
            x.value = '';
            x.focus();
            return false;
        }
    }
    return true;
}
Note: The only between these two functions is, the Example 2 will popup a message box indicating end user to provide numeric value.