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 on OnKeyPress
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 event OnKeyPress()
.
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!
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.