Allowing Only Numbers in ASP. NET TextBoxes – Use Regular Expression Validator!

[update 2012-07-16]

Kendo also has a numeric textbox input (both a widget and MVC extension), and Telerik has a numeric text input for ASP.NET Ajax.

[update 2011-10-07]

This continues to be a popular post, even though it was written in 2005.  If you need a solution for ASP.NET MVC, I’d suggest using a validation attribute on your model, and the Wijmo Complete Input jQuery UI widget (also available in the ASP.NET MVC Tools).

If you’re using WebForms, this method will still work, or you could look at the Wijmo-powered Input control.

[/update]

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 different 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)