TextBox which accepts only numbers






3.06/5 (12 votes)
Jul 15, 2005

177803

3234
An article on how to allow users to enter only numbers in a TextBox.
Introduction
In this example, I'll show you how to extend ASP.NET textbox so that it accepts only numbers as input. Users will not be allowed to enter anything other than numbers in the textbox.
Using the code
Well, the process of doing this is quite simple and straightforward. The entire job is done in the Jscript procedure which handles the textbox's OnKeyPress
event. Here are the steps involved to accomplish this:
- I have created is a simple Jscript procedure '
FilterNumeric()
' which filters users keyboard entries onOnKeyPress
event. Anything other than numbers, and '-', '.' are ignored. - The procedure is registered on the page.
Page.RegisterClientScriptBlock ("FilterNumeric", GetNumberValidatorScript());
- I have added an extra attribute to
txtNumber
control to handle the eventOnKeyPress()
.txtNumber.Attributes.Add ("onkeypress", "FilterNumeric()");
I have added a RegularExpressionValidator
to validate user entries on the server side. It uses the following expression:
(^[-]?[1-9]\d+$)|(^[-]?[1-9]$)|(^0$)|(^[-]?[1-9]\d+\.\d$)|(^[-]?[0-9]\.\d$)
and it allows: {123134456;4341643.2}.
Hope it helps someone!