How to Allow Only Numbers in HTML TextBox Using Javascript

Sometimes you want to constrain what a user can enter in a textbox input on a page. This article shows you an easy way to do it with javascript and explains how it works. In short, you want to trap the onkeypress event of the input control, verify that the key the user pressed is a numeric key and either accept the input or reject it. First, let’s create a simple page with a form that contains a text input and a submit button:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<title>Create a Text Input That Accepts Only Numbers</title>
</head>
<body>
	<form>
		<input type="text" id="myInput" name="myInput" onkeypress="return isNumericKey(event);" /><br />
		<input type="submit" id="mySubmit" name="mySubmit" value="Submit My Number" onclick="return submitMyNumber();" />
	</form>
</body>
</html>

The first thing to note here is that we defined the onkeypress event on the input control that calls the isNumericKey(event) javascript function. The function will return a boolean value indicating whether the keystoke should be accepted (true) or rejected (false). Do not worry about the submit button – we will come back to that later. So, let’s implement the isNumericKey(event) function:

function isNumericKey(e)
{
	if (window.event) { var charCode = window.event.keyCode; }
	else if (e) { var charCode = e.which; }
	else { return true; }
	if (charCode > 31 && (charCode < 48 || charCode > 57)) { return false; }
	return true;
}

Now let’s go through what happens here. The first thing to notice is that it accepts a parameter and that we are passing in event from our input. event is a standard variable in most modern browsers and is an object that contains details about the event that occurred. It is, however, a good practice to support backwards compatibility – thus in our function we first check if window.event, a legacy IE object, is defined. If it is, we can retrieve the ASCII character code from the keyCode property. If that’s not the case, we still need to check if the parameter we passed is defined – if the browser does not support it, we do not want to get a javascript error. In this case (second else), let’s just accept the keystroke. Otherwise, the character code can be retrieved from the which property. Note that the charCode variable has var in front of it – we want the scope of this variable to be within the function only.

Now that we have the character code, it’s simple: let’s make sure the ASCII code is that of a numeric key, being a value between 48 (0) and 57 (9) and that it’s not a control code (control control codes are those below 32). If you look at the if statement above, you’ll notice that it’s a negation of what I just said. You’ll also notice that such a negation returns false, rejecting the keystroke.

Now that we are in the clear, we can be certain that the key fed to the input is a digit and we can accept it by returning true. Try it yourself by loading this page and typing something in the textbox:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<title>Create a Text Input That Accepts Only Numbers</title>
	<script type="text/javascript">
	function isNumericKey(e)
	{
		if (window.event) { var charCode = window.event.keyCode; }
		else if (e) { var charCode = e.which; }
		else { return true; }
		if (charCode > 31 && (charCode < 48 || charCode > 57)) { return false; }
		return true;
	}
	</script>
</head>
<body>
	<form>
		<input type="text" id="myInput" name="myInput" onkeypress="return isNumericKey(event);" /><br />
		<input type="submit" id="mySubmit" name="mySubmit" value="Submit My Number" onclick="return submitMyNumber();" />
	</form>
</body>
</html>

Now let’s go back to the submit button – with the developer tools readily available, you can easily circumvent the validation that we just implemented. If you, for instance, have FireBug addon for Firefox, while you would not be able to type in letters in the textbox, you could easily invoke the inspect element function and modify the value in the textbox through the addon. The isNumericKey function in this case only provides a restriction. What you always want is also validating your input before it’s submitted to the server. As always, it is a good idea to provide client-side validation as well as server-side validation. The former will ensure the user doesn’t have to wait for the page to reload and latter will ensure the data is validation without the user bypassing validation. So, keeping in mind that server-side validation is still needed, let’s implement a javascript function that will do final validation of our input:

function submitMyNumber()
{
	var input = document.getElementById('myInput').value;
	return input.match(/^[0-9]+$/) != null;
}

This is a very simple function that uses a regular expression to validate that the texbox text is all digits. Also note that the regular expression expects at least one digit so you will not be able to submit a blank value. So, our final page looks like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<title>Create a Text Input That Accepts Only Numbers</title>
	<script type="text/javascript">
	function isNumericKey(e)
	{
		if (window.event) { var charCode = window.event.keyCode; }
		else if (e) { var charCode = e.which; }
		else { return true; }
		if (charCode > 31 && (charCode < 48 || charCode > 57)) { return false; }
		return true;
	}
	function submitMyNumber()
	{
		var input = document.getElementById('myInput').value;
		return input.match(/^[0-9]+$/) != null;
	}
	</script>
</head>
<body>
	<form>
		<input type="text" id="myInput" name="myInput" onkeypress="return isNumericKey(event);" /><br />
		<input type="submit" id="mySubmit" name="mySubmit" value="Submit My Number" onclick="return submitMyNumber();" />
	</form>
</body>
</html>
Share on Tumblr
2e307f11274d16b211fd7199e5091b0e
Submit to redditShare on MyspaceShare via email
This entry was posted in Javascript and tagged , , , , , , , , , . Bookmark the permalink.
1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 3.33 out of 5)
Loading ... Loading ...

One Response to How to Allow Only Numbers in HTML TextBox Using Javascript

  1. Pingback: Creating A Phone Number Input Control With Javascript | ℓūfħer Ṭecħᵒ