How to validate phone numbers with PHP

Okay I have been teaching myself PHP form processing and validation.

What I’m trying to do is validate a form field that requires numbers. How do I do this?
I searched google and found some codes but nothing looks good.

The problem is this, I want the error message to appear in the form label.

So far this is what I have done but when I submit the form, even with a valid format number, I’m still getting error message that the number is not valid.

The code:


<?php

  $error = '';
  if(array_key_exists('phoneNumber', $_POST))
  {
    if(!preg_match('/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/', $_POST['phoneNumber']))
    {
      $error = 'Invalid Number!';
    }
  }

?>
<div class="phone_fieldWrapper">
<label for="phoneNumber">Phone Number: <span class="warning"> <?php echo $error; ?></span></label>
  <input name="phoneNumber" type="text" class="phoneNumber_inputControl" id="phoneNumber" />

Any ideas,

Thanks - IC

Are you entering a valid number in the form (XXX-XXX-XXXX)? The expression matches that correctly, I don’t see this code as the cause of it failing.

I finally figured it out, The problem was the number in the last curly bracket should be 4 not 3. I know it shows four in my post here but in the web page I noticed 3 and that should have been four.
That’s because the last sets of digits of the phone number is four not three. Eg: 5555.

Anyway, thanks very much,

IC.

Remember that not all phone numbers follow that format. My (UK) number is in the format xxxxx xxxxxx - but if you’re only catering for US residents then I guess that doesn’t matter :slight_smile:

Even US residents type their number many different ways, and sometimes put a 1 in front of the whole thing.

Hey Dan, what I did was added and example of how the number should be enter, this is near the input field and will give user the hint as to how they should enter the number. Eg: U.S only 555-555-555

Thanks for all your help.

IC