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.

Be Sociable, Share!

12 Responses to “Number only TextBox”

  1. Dhirendra Singh Says:

    thanks buddy….

  2. Tamir Khason Says:

    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

  3. Jim Says:

    EternalFlame uncovers the "space" conspiracy.  WHY NO ANSWERS?  Why will no one answer the question as to why space is not considered "text input"!?

  4. EternalFlame Says:

    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′

  5. Karl Shifflett Says:

    Tamir,

    Thank you for the very quick response.

    Cheers,

    Karl

  6. Tamir Khason Says:

    Karl, you can do the same on TextChanged event and handle pasted input

  7. Karl Says:

    Hi,

    I was also wondering of the solution you came up with to handle Copy/Paste operations on a TextBox.

    Thanks!

    Karl

  8. Snippet: Numeric only textbox | Hodson Report Says:

    Pingback from  Snippet: Numeric only textbox | Hodson Report

  9. mcarbenay Says:

    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.

  10. Noticias externas Says:

    There are a lot of cases, you have to validate, that user inputs numbers only into TextBox. Someone things

  11. My Personal Blog » Number only TextBox Says:

    Pingback from  My Personal Blog &raquo; Number only TextBox

  12. Dusauttessy Says:

    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,

Leave a Reply

Recommended

 


Sponsor


Partners

WPF Disciples
Dreamhost
Code Project
Switched to Better Place

Together