6

Possible Duplicate:
How do I make a textbox that only accepts numbers?

I have a phone number that I wish to store as a string.

I read this in using

txtHomePhone.Text

What I think I need is some kind of is numeric but can't get it working

if (txtHomePhone.Text == //something.IsNumeric)
{
    //Display error
}
else
{
    //Carry on with the rest of program ie. Add Phone number to program.
}

What is the best way to allow only numeric values to be entered?

4
  • Does txtHomePhone represent a TextBox? If so, you may use the KeyPress event to accept the characters you would like to allow and reject what you would not like to allow to be entered in the TextBox. Have a great day :) Commented Nov 6, 2012 at 14:35
  • It does represent a textbox, how do I find out which keypress is which? Commented Nov 6, 2012 at 14:37
  • Is this a web or client application? Commented Nov 6, 2012 at 14:38
  • Springfox, look at the link provided by @TyrionLannister - the first answer has some code showing you how to handle keypress events and only let digits through. If you'd prefer to keep your IF functionality above, look at davenewza's answer below (TryParse). You can also use Regex to match more complex strings and detect if a string is using a "(xxx) xxx-xxxx" format, for instance. Commented Nov 6, 2012 at 14:42

6 Answers 6

11

Since txtHomePhone represents a TextBox, you may use the KeyPress event to accept the characters you would like to allow and reject what you would not like to allow in txtHomePhone

Example

public Form1()
{
    InitializeComponent();
    txtHomePhone.KeyPress += new KeyPressEventHandler(txtHomePhone_KeyPress);
}
private void txtHomePhone_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '') //The  character represents a backspace
    {
        e.Handled = false; //Do not reject the input
    }
    else
    {
        e.Handled = true; //Reject the input
    }
}

Notice: The following character (which is not visible) represents a backspace.
Notice: You may always allow or disallow a particular character using e.Handled.
Notice: You may create a conditional statement if you would like to use -, , ( or ) only once. I would recommend you to use Regular Expressions if you would like to allow these characters to be entered in a specific position.

Example

if (e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '') //The  character represents a backspace
{
    e.Handled = false; //Do not reject the input
}
else
{
    if (e.KeyChar == ')' && !txtHomePhone.Text.Contains(")"))
    {
        e.Handled = false; //Do not reject the input
    }
    else if (e.KeyChar == '(' && !txtHomePhone.Text.Contains("("))
    {
        e.Handled = false; //Do not reject the input
    }
    else if (e.KeyChar == '-' && !textBox1.Text.Contains("-"))
    {
        e.Handled = false; //Do not reject the input
    }
    else if (e.KeyChar == ' ' && !txtHomePhone.Text.Contains(" "))
    {
        e.Handled = false; //Do not reject the input
    }
    else
    {
        e.Handled = true;
    }
}

Thanks,
I hope you find this helpful :)

Sign up to request clarification or add additional context in comments.

2 Comments

allow 123( for example i tried it in visual basic .net
Super helpful answer, thank you. I had to use e.KeyChar=='\b' to capture the backspace (instead of e.KeyChar=='') in the Visual C# MVStudio environment. I used your pattern for accepting one instance of a specific character, to accept a decimal point in my numeric value.
7

I'm assuming that you are using Windows Forms here, have a look at the MaskedTextBox. It allows you to specify an input mask of characters.

txtHomePhone.Mask = "##### ### ###";

Since this allows you to restrict the input values, you can safely parse the value to an integer.

Note: If you are using WPF, I don't think there is a MaskedTextBox in the base libraries, however there are extensions available on NuGet which may provide similar functionality.

6 Comments

He's looking for a way to validate that the numbers are numeric, not hide what is there.
The mask specifies the allowed characters, it doesn't hide the input in the same was as a password input mask.
@TyrionLannister A Maskedtextbox doesn't hide the value it forced the input to conform to the "mask". SO in Trevor's example the text box will only show 11 numbers in the format "##### ### ###". The spaces are forced in there.
My apologies. It's early, and I read "Mask".
@TyrionLannister - easily done, we've all been there :o)
|
5

To check to see if a numeric value has been entered, you can use Integer.TryParse

int num;
bool isNum = Integer.TryParse(txtHomePhone.Text.Trim(), out num);

if (!isNum)
    //Display error
else
    //Carry on with the rest of program ie. Add Phone number to program.

BUT remember that telephone numbers aren't necessarily only numeric. Refer to Trevor Pilley answer for a masked textbox.

Comments

3

Try this

if (!txtHomePhone.Text.All(c=> Char.IsNumber(c)))
{
    //Display error
}
else
{
    //Carry on with the rest of program ie. Add Phone number to program.
}

2 Comments

What does that do? It gives you a true/false value, but doesn't give any real validation. (Also, for the telephone number example used in the original question, it may not be sufficient: it'll return false for symbols and whitespace that might be in a typical phone number input.)
@DanPuzey In his example he wrote specifically: if (txtHomePhone.Text == //something.IsNumeric ). So i figured there are no whitspaces etc. And about validation, all he has to do is check the isNumeric. I added the code to the if statement to better explain.
0

Usually I would use Integer.TryParse as davenewza recommended, but another alternative is to use the VisualBasic IsNumeric function from C#.

Add a reference to the Microsoft.VisualBasic.dll file and then use the following code.

if (Microsoft.VisualBasic.Information.IsNumeric(txtHomePhone.Text))
{
    //Display error
}
else
{
    //Carry on with the rest of program ie. Add Phone number to program.
}

Comments

0

The best way I've found to do this is to only allow the user to enter the numeric keys into the text box, thanks for your help.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.