Wizard
Wizard

Reputation: 1152

Validating a numeric textbox

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.

Upvotes: 0

Views: 265

Answers (5)

Luiz Angelo
Luiz Angelo

Reputation: 336

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?

Upvotes: 0

andy
andy

Reputation: 6079

Regex regex = new Regex(@"^\d$");

Refer for Details: Regex for numbers only

Upvotes: 0

Danilo Vulović
Danilo Vulović

Reputation: 3063

Regex staffNumVal = new Regex(@"^\d*$");

Upvotes: 1

Mihai
Mihai

Reputation: 2760

Try it like so

int value;
if (int.TryParse(txtStaffHPhone.Text, out value))
{
    // it's a valid integer 
}

Upvotes: 0

Priyank Patel
Priyank Patel

Reputation: 6996

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");
}

Upvotes: 2

Related Questions