How to Only Allow Numbers in A TextBox

October 13, 2008

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.NET Code


<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.

Advertisements