0

I'm trying to validate a textbox to check that it has a phone number type value entered.

The problem I'm having is that even when the entry is for example: "blah" in these text boxes the Regex is still returning false and no error message is shown.

Regex staffNumVal = new Regex(@"^[a-z]+$");

if (staffNumVal.IsMatch(txtStaffHPhone.Text)||(staffNumVal.IsMatch(txtStaffHourRate.Text)))
{
   MessageBox.Show("Please enter a numeric value");
}

Is there a better way to do this that I'm missing? Thanks.

Wizard
  • 1,104
  • 3
  • 14
  • 36
  • Can you be sure there is no whitespace? If your values need trimming or contain whitespace that Regex won't match... – Paul D'Ambra Nov 06 '12 at 12:10

6 Answers6

2

Instead of

Regex staffNumVal = new Regex(@"^[a-z]+$");

Use

Regex staffNumVal = new Regex(@"^[0-9]+$");

if (staffNumVal.IsMatch(txtStaffHPhone.Text)||(staffNumVal.IsMatch(txtStaffHourRate.Text)))
{
  //Valid
}
else
{
  MessageBox.Show("Please enter a numeric value");
}
Priyank Patel
  • 6,708
  • 10
  • 54
  • 86
1
Regex staffNumVal = new Regex(@"^\d*$");
Danilo Vulović
  • 2,875
  • 18
  • 31
0

Try it like so

int value;
if (int.TryParse(txtStaffHPhone.Text, out value))
{
    // it's a valid integer 
}
Mihai
  • 2,662
  • 28
  • 43
0
Regex regex = new Regex(@"^\d$");

Refer for Details: Regex for numbers only

Community
  • 1
  • 1
andy
  • 5,802
  • 2
  • 25
  • 49
0

Your RegEx does not do what you expect it.

I think the '^' is misplaced. It should be: @"[^a-z]+$".

But even that is wrong, since it accepts things like &.

You can test at: http://regexhero.net/tester/

But I think you'll be better served with a MaskedTestBox. Have you tried that?

Luiz Angelo
  • 326
  • 2
  • 11
-1

Import Microsoft.VisualBasic and use it!

if (Microsoft.VisualBasic.Information.IsNumeric("5"))
{
//Do Something
}
m4ngl3r
  • 540
  • 2
  • 17