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,142
  • 3
  • 16
  • 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

5 Answers5

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,898
  • 11
  • 58
  • 88
1
Regex staffNumVal = new Regex(@"^\d*$");
Danilo Vulović
  • 2,983
  • 20
  • 31
0

Try it like so

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

Refer for Details: Regex for numbers only

Community
  • 1
  • 1
andy
  • 5,979
  • 2
  • 27
  • 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
  • 336
  • 3
  • 12