Number only TextBox
There are a lot of cases, you have to validate, that user inputs numbers only into TextBox. Someone things, that it’s bad behavior to prevent user from typing well-known bad characters. I think, it’s good. Let’s take an example of form, you have to enter Social ID. Do you really think, that user expects the form tell him: "Hey, you, it’s 9 digits only. You typed ‘Z’, which is not digit. Don’t do it anymore…". I think, that the good behavior is when user types Z in text area for social id, nothing should happens. But, anyhow, it’s up to you to decide.
Today, I want to explain how to build TextBox, that accepts only numbers in WPF.
In WinForms world, we used to handle KeyDown or KeyPressed event to get character and check whether it number. In WPF world, there are a lot of ways to input anything, that text (for example Voice recognition or handwriting. More then this, in WPF (device independent) world we can not be sure, that when you press key with 2 and @ in your keyboard without Shift pressed, you meant "2". Thus KeyDown or, even PreviewKeyDown event will not bring you salvation. We should handle input text without relation to input device. For this purpose, we have TextInput and PreviewTextInput event. Let’s handle it
public class NumberTextBox:TextBox
{protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e)
{
e.Handled = !AreAllValidNumericChars(e.Text);
base.OnPreviewTextInput(e);
}}
Pretty cool, ah? What’s about validation itself? "5" is definitely number, but what about "٥" ? Well, it’s five in Arabic and it’s number too. Is ‘½’ is number? Sure, it’s a half, but is it digit? No! This why we should use Char.IsDigit method, rather then Char.IsNumber which is not limited to radix 10 digits. The same behavior, you’ll get using Char.GetUnicodeCategory method to compare to UnicodeCategory.DecimalDigitNumber, but in this case, it will be current culture oriented.
Well. now we know if the input it decimal, what’s about 1,000.00 numbers? The simplest way is to check whether the char is ‘.’{0x2e} or ‘,’ {0x2c} and mark it as valid, however, what’s about 1’00”00 or 100° which is absolutely valid numbers? NumberFormatInfo.CurrentInfo is your best friend in this case. You can always check my Globalization statements by using this handy program.
Now, when we sure, that everything is ok, we can write the test method
bool AreAllValidNumericChars(string str)
{
bool ret = true;
if (str == System.Globalization.NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.CurrencyGroupSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.CurrencySymbol |
str == System.Globalization.NumberFormatInfo.CurrentInfo.NegativeSign |
str == System.Globalization.NumberFormatInfo.CurrentInfo.NegativeInfinitySymbol |
str == System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.NumberGroupSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.PercentDecimalSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.PercentGroupSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.PercentSymbol |
str == System.Globalization.NumberFormatInfo.CurrentInfo.PerMilleSymbol |
str == System.Globalization.NumberFormatInfo.CurrentInfo.PositiveInfinitySymbol |
str == System.Globalization.NumberFormatInfo.CurrentInfo.PositiveSign)
return ret;int l = str.Length;
for (int i = 0; i < l; i++)
{
char ch = str[i];
ret &= Char.IsDigit(ch);
}return ret;
}
The only thing we should do is handle drag and drop and paste whole text into the textbox. That’s all folks. If you want to know how to handle and validate D&D and paste, let me know.
November 14th, 2007 · Comments (12)
12 Responses to “Number only TextBox”
Leave a Reply
Discover other tags
My tools
- .NET Framework Detector
- Duplicate images finder
- Exchange Security Policy for Windows Mobile Devices Fix
- Gas Price Windows Vista SideBar gadget
- Israel Traffic Information Windows Vista SideBar gadget
- Localization fix for SAP ES Explorer for Visual Studio
- LocTester
- RTL and LTR in Windows Live Writer
- Silverlight controls library
- Snipping tool integration plugin for WLW
- USB FM receiver library
- Vista Battery Saver
- WebCam control for WPF
- Windows Live SkyDrive attachment for Windows Live Writer
- Wireless Migrator
- WPF Virtual Keyboard





January 1st, 2009 at 12:27 am
thanks buddy….
January 1st, 2009 at 12:27 am
Jim, EternalFlame,
Space (as well as backspace) are not treated as text composition, thus the workaround for spaces is handling KeyDown (PreviewKeyDown) and firing the event
January 1st, 2009 at 12:27 am
EternalFlame uncovers the "space" conspiracy. WHY NO ANSWERS? Why will no one answer the question as to why space is not considered "text input"!?
January 1st, 2009 at 12:27 am
This solution doesn’t work with space char’s!!!
OnPreviewTextInput isn’t called when you enter a space!
you can get wrong entries like: ’99 123 8′
January 1st, 2009 at 12:27 am
Tamir,
Thank you for the very quick response.
Cheers,
Karl
January 1st, 2009 at 12:27 am
Karl, you can do the same on TextChanged event and handle pasted input
January 1st, 2009 at 12:27 am
Hi,
I was also wondering of the solution you came up with to handle Copy/Paste operations on a TextBox.
Thanks!
Karl
January 1st, 2009 at 12:27 am
Pingback from Snippet: Numeric only textbox | Hodson Report
January 1st, 2009 at 12:27 am
Hi, I was wondering if you have posted a follow-up example with Copy/Paste handling somewhere or if you would be so kind as to write a little post about how to do that.
January 1st, 2009 at 12:27 am
There are a lot of cases, you have to validate, that user inputs numbers only into TextBox. Someone things
January 1st, 2009 at 12:27 am
Pingback from My Personal Blog » Number only TextBox
February 2nd, 2012 at 7:55 pm
has much better facilities of customer treatment and delivery. Certainly, when you make the acquisition at the officiallesser prices than acquiring them individually. Women’s Enjoy For Chanel Handbags Chanel is among the mostyour city. Often the shop timings do not match your schedules, and at other occasions the shop is oftenhave the funds for to acquire new bags, second hand bags are without a doubt an extremely sensible different. The trick merely lies inyour curiosity and distinct your doubts just before you make the purchase. Within a bodily retail store, it’s possible you’ll come to feel [url=http://www.classicchanelbagsale.com]chanel outlet[/url] avail over there. The costs that you discover for the Chanel on the net store are substantially a lot less when compared with what youthe vendor offered on their profiles, or based upon which vendor is closer in your home, you are able to easily filterChanel, including jewelry and various add-ons. Pictures are uploaded because of the sellers making sure that the buyer canis Osceola Flea Market, wherever you could find every little thing from contemporary deliver to antiques to Florida merchandise.choose to shop while you are sitting at the airport browsing the world wide web, even though waiting around to board your flight,