0

EDIT: I don't need the regex for the phone number, I have that already. What I need is help understanding how to insert that into my existing code, which I linked above. If you actually read my question, you'd see that I'm trying to learn what I need to modify in my original piece of code, not just copy and paste someone else's regex without knowing what to do with it. Thanks! EDIT x2: I figured it out.. Thanks anyway. (See answer below)

I have a piece of code that works to make sure something is in the phone field:

if (!empty($_POST['hphone'])) {$hphone = $_POST['hphone'];} else {$hphone = NULL; echo '<span class="error">Please enter a home phone number.</span><br />';}

In order to be more precise, I figured I'd try and make it check that it's a valid phone number. I found an example and tried to combine them:

if (!empty($_POST['hphone']) && !preg_match("/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i", $phone)) {$hphone = $_POST['hphone'];} else {$hphone = NULL; echo '<span class="error">Please enter a home phone number.</span><br />';}

This works in that the form still submits but it doesn't catch that there's a letter in the field. It just submits. I modified it some more to where it says there's not a valid number even though it is. I'm not a PHP guru so I'm just trying to do what makes sense to me with what I've got to work and other people's examples. Sorry for yet another post about this but I couldn't find exactly what I was after. Thanks!

ANSWER: I ended up figuring it out a different way. Below is the code that worked for me:

if (preg_match("/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i", $_POST['hphone'])) { $hphone = $_POST['hphone']; } else { $hphone = NULL; echo '<span class="error">invalid</span>'; }
user
  • 113
  • 1
  • 9
  • 1
    Here is the best place to look - http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation – Telshin Nov 02 '13 at 20:32
  • 2
    *"If not empty __and__ doesn't match the regex..."* What about if it's only empty? You want an `||` here! – deceze Nov 02 '13 at 20:33
  • Thank you Tim, but that doesn't answer my question at all. It gives me the regex stuff for the phone number but doesn't help explain how to insert it into my existing code. Thank you deceze for actually offering a potential solution for me. I'll see what I can find out. The rest of you, thanks for just writing this off as "another question that's already been answered, here, let's be a jerk and just link to something else...." If you read my question, you'll see that I have a string of code that I need to figure out how to insert the phone validation. Just giving me the regex doesn't help. – user Nov 03 '13 at 12:55
  • Deceze - I tried that and it didn't work. I did get it to work eventually though. I just had to get rid of all of the existing validation and just stick in the regex part and it worked. – user Nov 03 '13 at 16:29

0 Answers0