How to Only Allow Numbers in A TextBox

I came across a problem the other day. I was working on a ASP.NET application written on the .NET 1.1 Framework and I need to restrict two text box controls to only allow numbers. Being written for 1.1, I did not have access to the slick AJAX Control Toolkit which I could had easily thrown on a extender to force only numbers, thus I had to resort to good old JavaScript!

There actually were lots of examples of doing this on the Internet, but it was challenging to find one that worked period or would work in multiple browsers! Finally, after doing extensive searches and tweaks, here is the final function I used to restrict a text box to only accept numbers:

Javascript Function

// A function that only allows numbers to be typed into a text field.
function NumberValidation(event)
var charCode = (event.which) ? event.which : event.keyCode;

return !(charCode > 31 && (charCode < 48 || charCode > 57));


<asp:TextBox ID="PageSize" Runat="server" style="width:30px;" MaxLength="3" OnKeyPress="return NumberValidation(event);"></asp:TextBox>

*Note: Even though Visual Studio will indicate you cannot have OnKeyPress in the aspx, you can still put it there and it will work.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: