Click here to Skip to main content
15,883,884 members
Articles / Programming Languages / C#

Numbers and Characters only Textbox Validation in C# !

Rate me:
Please Sign up or sign in to vote.
4.75/5 (23 votes)
5 Jul 2011CPOL4 min read 228.7K   7.3K   32   32
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.

C#
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.

C#
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.

C#
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).

C#
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.

C#
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 '#'.

C#
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 :)

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)


Written By
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

Comments and Discussions

 
QuestionThe TextChanged action is not showing options as defined Pin
Member 1200872728-Sep-15 20:37
Member 1200872728-Sep-15 20:37 
QuestionThanks For helping Pin
Member 1152892816-Mar-15 3:06
Member 1152892816-Mar-15 3:06 
QuestionThanx man Pin
Emily GaGnon6-Feb-15 7:43
Emily GaGnon6-Feb-15 7:43 
AnswerAll validation in c# using single line of code.. Pin
Tushar Jagdale11-Oct-14 1:45
professionalTushar Jagdale11-Oct-14 1:45 
AnswerThank you so much! Pin
andy.g1024-Jul-14 8:24
andy.g1024-Jul-14 8:24 
GeneralRe: Thank you so much! Pin
andy.g1024-Jul-14 8:34
andy.g1024-Jul-14 8:34 
SuggestionRe: Copy/Paste problem solved... Pin
Giuseppe Pischedda25-Jul-14 23:27
Giuseppe Pischedda25-Jul-14 23:27 
GeneralRe: Copy/Paste problem solved... Pin
andy.g1028-Jul-14 11:49
andy.g1028-Jul-14 11:49 
GeneralMy vote of 4 Pin
Mohammad Sharify1-Jul-13 0:28
Mohammad Sharify1-Jul-13 0:28 
GeneralMy vote of 5 Pin
alhashdi31-Mar-13 22:08
alhashdi31-Mar-13 22:08 
QuestionProblem with Paste Pin
Rami Awad O.10-Jan-13 7:38
Rami Awad O.10-Jan-13 7:38 
AnswerRe: Problem with Paste Pin
Mahmoud Hesham El-Magdoub10-Jan-13 7:54
Mahmoud Hesham El-Magdoub10-Jan-13 7:54 
GeneralMy vote of 5 Pin
Abhilash Hari26-Dec-12 7:04
Abhilash Hari26-Dec-12 7:04 
Questionhow allow only number in text box with (:) Pin
PhDrMaryGirgis7-Dec-12 7:20
PhDrMaryGirgis7-Dec-12 7:20 
GeneralMy vote of 5 Pin
Bünyamin Akseli29-Sep-12 0:54
Bünyamin Akseli29-Sep-12 0:54 
GeneralRe: My vote of 5 Pin
Mahmoud Hesham El-Magdoub29-Sep-12 1:06
Mahmoud Hesham El-Magdoub29-Sep-12 1:06 
GeneralRe: My vote of 5 Pin
Bünyamin Akseli29-Sep-12 1:17
Bünyamin Akseli29-Sep-12 1:17 
GeneralRe: My vote of 5 Pin
Mahmoud Hesham El-Magdoub29-Sep-12 1:39
Mahmoud Hesham El-Magdoub29-Sep-12 1:39 
QuestionAssumptions Pin
GalleySlave24-Feb-12 5:56
GalleySlave24-Feb-12 5:56 
Mahmoud,

Interesting solution I won't cover some valid points made above
(there is room for this beside masked text boxes which have their own limitations & exceptions in something like this with a user interface aren't expensive - the user will spend some time interpreting the feedback anyway.)

You do assume though that only method of entry is keypress - if so you should handle this with the on keypress event - for full validation on textchanged, you should note that the text may also be changed programatically; or by the user pasting a number in.
In these cases the SelectionStart will not be in the correct place, so you would need another method.
AnswerRe: Assumptions Pin
Mahmoud Hesham El-Magdoub24-Feb-12 6:00
Mahmoud Hesham El-Magdoub24-Feb-12 6:00 
QuestionJust a tip. Pin
ksanghavi22-Feb-12 10:36
ksanghavi22-Feb-12 10:36 
AnswerRe: Just a tip. Pin
Mahmoud Hesham El-Magdoub24-Feb-12 6:07
Mahmoud Hesham El-Magdoub24-Feb-12 6:07 
GeneralMy vote of 5 Pin
ramakrishnankt7-Jul-11 4:05
ramakrishnankt7-Jul-11 4:05 
QuestionAn interesting discussion but not really good enough to replace standard validation solutions Pin
John Brett5-Jul-11 22:28
John Brett5-Jul-11 22:28 
QuestionExtention - Money Pin
hardsoft5-Jul-11 17:24
hardsoft5-Jul-11 17:24 

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

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