This article came up on the news today: Allowing Only Numbers in ASP.NET Textboxes. In this article, Bipin uses a custom validator to enforce input. I usually like Bipin's ideas, but this one seems to be a little more difficult than it needs to be.
I think there's a better way to do this--use a regular expression validator. To test this, create a page, and add a textbox, regular expression validator, and a button. For the validation expression, enter the following:
^[0-9]+$
Compile your page and test with some diffrerent inputs.
A quick explanation of the expression:
^ indicates the start of the input
[0-9] indicates a range of allowable characters. You could do [0,1,2,3,4,5,6,7,8,9], but that's not lazy.
+ indicates 'match preceeding one or more times'
$ indicates the end of input
If you wanted to enforce a length of input, you could do something like:
^[0-9]{6,12}$
which would enforce a minimum of 6 characters and a max of 12.
I think regular expressions are too often overlooked, but they're very powerful and simple once you work with them a little bit. For a good basic overview of regular expressions, check out
The Web Professional's Handbook
And a more in-depth RegEx reference in:
Pure JavaScript: 2nd Ed. (an absolute steal if you buy it used)
Regular Expressions with .NET [DOWNLOAD: PDF]
Downloadable e-bok in PDF format, from Amazon.
Mastering Regular Expressions, Second Edition (The Owl Book)
<edit>
Thinking about Joseph's comments below, one could extend Bipin's idea and use a regular expression instead of parsing the string and checking to see if each character is numberic or a period. You could also add in a check to see if the field was blank, and save on the second validator.
</edit>