Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

Numbers and Characters only Textbox Validation in C# !

, 5 Jul 2011
Rate this:
Please Sign up or sign in to vote.
Filter your Textbox to Integers, Characters or doubles only in C# , Create customized numeric alphabetic texboxes

Introduction

Handling a Textbox exception is a very common task and found in nearly every GUI. Usually the handling of a Textbox is the process of permitting the user to write only numbers (whether integers or real) or alphabetical characters. All the code I've found on the net tackles this issue with regular expressions, it works well but has some limitations. In this article, I do the Textbox exception handling in a different, easy and flexible way.

Using the Code

The way of doing this is quite simple and straight forward. I mainly work on the "TextChanged" action of the TextBox. There are three main types of functions I used for the "TextChanged" action and they are:

  1. validateTextInteger()
  2. validateTextDouble()
  3. validateTextCharacter()

The validateTextInteger() function permits the user to only type positive or negative Integer values, the validateTextDouble() function permits the user to write positive or negative double values only and finally the validateTextCharacter() function only allows the user to write alphabetical characters.

To use any of these functions, the user simply selects a Textbox then goes to the actions panel and on the "TextChanged" row, he selects one of these three functions according to the exception handling he desires.

Choose_Actions.png

Validations.png

These three functions are normal validation functions, to make them more flexible I made another three customized functions and they will be discussed in detail in the Customized Validations section.

ValidateTextInteger

I parse the text to an integer and if all is ok, nothing will be changed but if the parsing function throws an exception, I catch it and remove the new character that made this exception then I rearrange the textbox cursor back to its place. I check the text and if it's equal to the minus sign I leave it as it is because the parsing function would throw an exception if the text is only a minus sign.

private void validateTextInteger(object sender, EventArgs e)
    {
        Exception X = new Exception();

        TextBox T = (TextBox)sender;

        try
        {
            if (T.Text != "-")
            {
                int x = int.Parse(T.Text);                 
            }
        }
        catch (Exception)
        {
            try
            {
                int CursorIndex = T.SelectionStart - 1;
                T.Text = T.Text.Remove(CursorIndex, 1);

                //Align Cursor to same index
                T.SelectionStart = CursorIndex;
                T.SelectionLength = 0;
            }
            catch (Exception) { }
        }
    }

Examples

When Pressed After Handling
11. 11
34a5 345
5_67 567

ValidateTextDouble

I parse the text to a double and if all is ok, nothing will be changed but the parsing function throws an exception. I catch it and remove the new character that made this exception then I rearrange the Textbox cursor back to its place.

I check the text and if it's equal to the minus sign, I leave it as it is because the parsing function would throw an exception if the text is only a minus sign. I also check if the text contains a comma ',' and throw an exception if found because the parsing function does not see the comma as an exception.

private void validateTextDouble(object sender, EventArgs e)
        {         
            Exception X = new Exception();

            TextBox T = (TextBox)sender;

            try
            {
                if (T.Text != "-")
                {
                    double x = double.Parse(T.Text);
                  
                    if (T.Text.Contains(','))
                        throw X;                    
                }
            }
            catch (Exception)
            {
                try
                {
                    int CursorIndex = T.SelectionStart - 1;
                    T.Text = T.Text.Remove(CursorIndex, 1);

                    //Align Cursor to same index
                    T.SelectionStart = CursorIndex;
                    T.SelectionLength = 0;
                }
                catch (Exception) { }
            }
        } 

Examples:

When Pressed After Handling
23.97. 23.97
0d.01 0.01
2$16 216

ValidateTextCharacter

I use the textContainsUnallowedCharacter() function to check if this new text contains a number or not, if it does not contain then nothing will be changed but if it contains a number I remove the new character (number) that made this exception then I rearrange the textbox cursor back to its place.

private void validateTextCharacter(object sender, EventArgs e)
    {            
        TextBox T = (TextBox)sender;
        try
        {
            //Not Allowing Numbers
            char[] UnallowedCharacters = { '0', '1',
                                           '2', '3', 
                                           '4', '5',
                                           '6', '7',
                                           '8', '9'};

            if (textContainsUnallowedCharacter(T.Text,UnallowedCharacters))
            {
                int CursorIndex = T.SelectionStart - 1;
                T.Text = T.Text.Remove(CursorIndex, 1);

                //Align Cursor to same index
                T.SelectionStart = CursorIndex;
                T.SelectionLength = 0;
            }
        }
        catch(Exception){ }
    }

    private bool textContainsUnallowedCharacter(string T, char[] UnallowedCharacters)
    {        
        for (int i = 0; i < UnallowedCharacters.Length; i++)
            if (T.Contains(UnallowedCharacters[i]))
               return true;

        return false;
    }

Examples:

When Pressed After Handling
ab6cd abcd
8tyhg tyhg
%$#@6 %$#@

Customized Validations

Other than these validations, I made some extra validations to make these functions more flexible, such as only permitting the user to enter positive integer values and disallowing the user to enter some specific characters. These functions are:

ValidateInetegerCustomized

This function is the same as validateTextInteger() but I add the customizing (filtering) condition which is 'if (x <= 0)', this only permits the user to write Integers from 1 to (2^31 -1).

private void validateTextIntegerCustomized(object sender, EventArgs e)
        {
            Exception X = new Exception();

            TextBox T = (TextBox)sender;

            try
            {                
                    int x = int.Parse(T.Text);

                   //Customizing Condition
                    if (x <= 0)
                        throw X;                
            }
            catch (Exception)
            {
                try
                {
                    int CursorIndex = T.SelectionStart - 1;
                    T.Text = T.Text.Remove(CursorIndex, 1);

                    //Align Cursor to same index
                    T.SelectionStart = CursorIndex;
                    T.SelectionLength = 0;
                }
                catch (Exception) { }

            }
        }         

Note: You can change this condition to 'if ( x < 0)' which will only permit the user to write Integers from 0 to (2^31 -1).

ValidateDoubleCustomized

This function is the same as validateTextDouble() but I add the customizing (filtering) condition which is 'if (x < 0)', this only permits the user to write positive double values.

private void validateTextDoubleCustomized(object sender, EventArgs e)
        {            
            Exception X = new Exception();

            TextBox T = (TextBox)sender;

            try
            {         
                    double x = double.Parse(T.Text);

                    //Customizing Condition (Only numbers larger than or 
		  //equal to zero are permitted)
                    if (x < 0 || T.Text.Contains(','))
                        throw X;              
            }
            catch (Exception)
            {
                try
                {
                    int CursorIndex = T.SelectionStart - 1;
                    T.Text = T.Text.Remove(CursorIndex, 1);

                    //Align Cursor to same index
                    T.SelectionStart = CursorIndex;
                    T.SelectionLength = 0;
                }
                catch (Exception) { }
            }
        }         

Note: You can change this condition to 'if ( x <= 0)' which will only permit the user to write positive double values starting from 1.

ValidateCharacterCustomized

This function is the same as validateTextCharacter() but here I change the values of the UnallowedCharacters array to not only disallow numbers but to also disallow the Underscore '_' and the Hash '#'.

private void validateTextCharacterCustomized(object sender, EventArgs e)
    {
        TextBox T = (TextBox)sender;          

        try
        {
            //Not Allowing Numbers, Underscore or Hash
            char[] UnallowedCharacters = { '0', '1',
                                           '2', '3', 
                                           '4', '5',
                                           '6', '7',
                                           '8', '9','_','#'};

            if (textContainsUnallowedCharacter(T.Text, UnallowedCharacters))
            {
                int CursorIndex = T.SelectionStart - 1;
                T.Text = T.Text.Remove(CursorIndex, 1);

                //Align Cursor to same index
                T.SelectionStart = CursorIndex;
                T.SelectionLength = 0;
            }
        }
        catch (Exception) { }
    }         

Note: You can change the values of this array to disallow the user to write any character you want.

GUI

The GUI is simple and is only used for illustration, it has 6 Textboxes where each one of these Textboxes uses one of the 6 functions discussed in this article.

Each_Textbox_Validation.png

History

1.0 (5 July 2011)

  • Initial release

Thank you for reading... I hope that this article would at least help anyone who is interested in this issue. If it did this, it would make me so happy Smile | :)

Don't take this article as the last solution! Try searching for regular expressions and masked Textboxes, maybe they will suit you better than this one.

Feel free to give me your comments on the code.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Mahmoud Hesham El-Magdoub
Software Developer (Senior) Free Lancer
Egypt Egypt
BSc Computer Engineering, Cairo University, Egypt.
 
I love teaching and learning and I'm constantly changing Smile | :)
Feel free to discuss anything with me.
 
A Freelance UX designer, Code is my tool brush, I design for experience !
 

My Website
Follow on   Twitter

Comments and Discussions

 
AnswerThank you so much! PinmemberMember 1092790824-Jul-14 8:24 
GeneralRe: Thank you so much! PinmemberMember 1092790824-Jul-14 8:34 
SuggestionRe: Copy/Paste problem solved... PinmemberGiuseppe Pischedda25-Jul-14 23:27 
GeneralRe: Copy/Paste problem solved... Pinmemberandy.g1028-Jul-14 11:49 
GeneralMy vote of 4 Pinmemberm0hammad.sh1-Jul-13 0:28 
GeneralMy vote of 5 Pinmemberalhashdi31-Mar-13 22:08 
QuestionProblem with Paste [modified] PinmemberRami Awad O.10-Jan-13 7:38 
AnswerRe: Problem with Paste PinmemberMahmoud Hesham El-Magdoub10-Jan-13 7:54 
GeneralMy vote of 5 Pinmemberabhilashelw26-Dec-12 7:04 
Questionhow allow only number in text box with (:) PinmemberPhDrMaryGirgis7-Dec-12 7:20 
i want to enter only numbers in text box with ( : )
as same as example
(10:10)
when write this code
<pre lang="cs">if ( char.IsDigit (e.KeyChar)||char .IsControl (e.KeyChar ))
            { e.Handled = false; }
 
            else e.Handled = true;</pre>
the text box allow only entered number but i want to add ( : )in text box with number
 
and when write this code not work <pre lang="cs">if ( char.IsDigit (e.KeyChar)||char .IsControl (e.KeyChar ))
                  { e.Handled = false; }
 
                  else e.Handled = true;
                  if (e.KeyChar == &#39;:&#39; &amp;&amp; (sender as TextBox).Text.IndexOf(&#39;:&#39;) &gt; -1)
                  { e.Handled = true; }</pre>
 
what can i solve this problem ??
GeneralMy vote of 5 PinmemberBünyamin Akseli29-Sep-12 0:54 
GeneralRe: My vote of 5 PinmemberMahmoud Hesham El-Magdoub29-Sep-12 1:06 
GeneralRe: My vote of 5 [modified] PinmemberBünyamin Akseli29-Sep-12 1:17 
GeneralRe: My vote of 5 PinmemberMahmoud Hesham El-Magdoub29-Sep-12 1:39 
QuestionAssumptions PinmemberGalleySlave24-Feb-12 5:56 
AnswerRe: Assumptions PinmemberMahmoud Hesham El-Magdoub24-Feb-12 6:00 
QuestionJust a tip. Pinmemberksanghavi@mantara.com22-Feb-12 10:36 
AnswerRe: Just a tip. PinmemberMahmoud Hesham El-Magdoub24-Feb-12 6:07 
GeneralMy vote of 5 Pinmemberramakrishnankt7-Jul-11 4:05 
QuestionAn interesting discussion but not really good enough to replace standard validation solutions PinmemberJohn Brett5-Jul-11 22:28 
QuestionExtention - Money Pinmemberhardsoft5-Jul-11 17:24 
AnswerRe: Extention - Money PinmemberMahmoud Hesham El-Magdoub5-Jul-11 18:57 
GeneralMy vote of 2 Pinmembernemopeti5-Jul-11 8:11 
GeneralRe: My vote of 2 PinmemberMahmoud Hesham El-Magdoub5-Jul-11 8:28 
GeneralRe: My vote of 2 Pinmembernemopeti5-Jul-11 8:40 
GeneralRe: My vote of 2 PinmemberMahmoud Hesham El-Magdoub5-Jul-11 8:49 
SuggestionExtending TextBox Pinmembervallarasus5-Jul-11 8:01 
GeneralRe: Extending TextBox PinmemberMahmoud Hesham El-Magdoub5-Jul-11 8:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 5 Jul 2011
Article Copyright 2011 by Mahmoud Hesham El-Magdoub
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid