In this short article I will explain how to perform Numeric validation in TextBox using jQuery in such a way that the TextBox will accept only numbers i.e. numeric values or digits in TextBox.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
body
{
font-size: 9pt;
font-family: Arial;
}
</style>
</head>
<body>
Numeric Value: <input type="text" id="text1" class = "numeric" />
<span class="error" style="color: Red; display: none">* Input digits (0 - 9)</span>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
var specialKeys = new Array();
specialKeys.push(8); //Backspace
$(function () {
$(".numeric").bind("keypress", function (e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
$(".error").css("display", ret ? "none" : "inline");
return ret;
});
$(".numeric").bind("paste", function (e) {
return false;
});
$(".numeric").bind("drop", function (e) {
return false;
});
});
</script>
</body>
</html>
Explanation:
In the above HTML Markup I have a TextBox for which we need to restrict the user enter only numeric values.
I have specified class property with value numeric to the TextBox so that we can access it via jQuery selectors.
On the window load event handler I have attached three event handlers to handle onkeypress, ondrop and onpaste events of the TextBox.
On the keypress event handler, first I have determined the ASCII code of the keyboard key and then verified that its ASCII code is within the range 48 to 57. I have also taken care of that the key pressed is not an special key like Backspace or Delete, if yes then that too is excluded
On the drop event handler, I have simply written return false so that the dropping functionality on the TextBox is disabled.
On the paste event handler, I have simply written return false so that the pasting functionality on the TextBox is disabled.
Demo
Downloads