Input validation – Numbers Only

Input validation – Numbers Only

Few times already I have been asked how can Input validation – Numbers Only be done. Well in c# it is actually very easy.
All You need to do is to add a key press event handler and check the currently pressed character.
If the character is what you want to allow, You can add it to the rest of text, else, just skip/ignore it.

Below You can find the example code as part of the key press event handler.
What this code does is: It validates the current input and only allows numbers to be added to the TexBox that is connected with the event handler. When I say number I mean digits only, one decimal separator and backspace for deleting. Code is written such a manner that a separator is retrieved from the machine settings, so you don’t have to worry if it is comma “,” or period “.”.


private void txtBox_NumbersOnly_Press(object sender, KeyPressEventArgs e)
{
e.Handled = ((!char.IsDigit(e.KeyChar)) && (e.KeyChar != '\b'));
char decimalSeparator = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
if (e.KeyChar == decimalSeparator)
{
TextBox tb = sender as TextBox;
e.Handled = tb.Text.Contains(decimalSeparator);
}
}

All You need to do in order to use it, is just to associate this event handler with some Texbox control.
Also at the top of the code, don’t forget to include the using statement below, or you will get compiler error at the CurrentCulture class

using System.Globalization;

Also as part of this tutorial I have included one more example of input validation. That is validation of custom characters. It checks in a predefined list of characters. If the current character is part of that list, then it is allowed to be entered in the validated TexBox. But, if it is not in the list, then the character is ignored.

Check the sample code below

private void txtBox_SpecialCharsOnly_Press(object sender, KeyPressEventArgs e)
{
//listAllowedChars is listbox with chars as items
e.Handled = !listAllowedChars.Items.Contains(e.KeyChar.ToString());
}

For demonstration purposes I have prepared a complete Windows Form Project that can be downloaded from here. It can be compiled with Visual studio 2010 or above.
Input validation - Numbers Only

Posted in C#, Programming, Tutorials, Visual Studio and tagged .

Leave a Reply

Your email address will not be published. Required fields are marked *