Ben P. Dorsi-Todaro
Ben P. Dorsi-Todaro

Reputation: 321

regex phone number validation with PHP

This is another question about a previous question I had asked yesterday. I want user to be allowed to type US phone numbers in the following formats.

(800)-555-1212

800-555-1212

and have it only check the database for numbers 8005551212

I've seen that regex like /^[\+]?([0-9]*)\s*\(?\s*([0-9]{3})?\s*\)?[\s\-\.]*([0-9]{3})[\s\-\.]*([0-9]{4})[a-zA-Z\s\,\.]*[x\#]*[a-zA-Z\.\s]*([\d]*)/

may work but I'm not certain how to implement it into the code from the link I provided

I'm new to php and know nothing about regex. Any help is appreciated.

Upvotes: 0

Views: 7827

Answers (5)

Donatas Navidonskis
Donatas Navidonskis

Reputation: 309

This function validate a phone number, return true if it validate and false if invalid. This function very simple i was wrote to.

    /**
     * @param $number
     *
     * @return bool
     */
    function validatePhoneNumber($number) {
        $formats = [
            '###-###-####', '####-###-###',
            '(###) ###-###', '####-####-####',
            '##-###-####-####', '####-####', '###-###-###',
            '#####-###-###', '##########', '#########',
            '# ### #####', '#-### #####'
        ];

        return in_array(
            trim(preg_replace('/[0-9]/', '#', $number)),
            $formats
        );
    }

Upvotes: 11

Hadderach
Hadderach

Reputation: 33

Re: Rohan Kumar's solution

<?php
$t='/\(?[2-9][0-8][0-9]\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}/';
$arr=preg_match($t,'(800)-555-1212',$mat);
$arr=preg_match($t,'800-555-1212',$mat);
print_r($mat);
?>

It does address the issue of fake phone numbers such as 800-123-2222. Real phone numbers have a first digit of at least "2". While the other solutions do the format correctly, they don't address the issue of people putting in phone numbers like 800-000-1234, which would be correct in the other solutions provided.

Upvotes: 0

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try this,

<?php
    $t='/\(?[2-9][0-8][0-9]\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}/';
    $arr=preg_match($t,'(800)-555-1212',$mat);
    $arr=preg_match($t,'800-555-1212',$mat);
    print_r($mat);
?>

Tested here

Upvotes: 0

Taleh Ibrahimli
Taleh Ibrahimli

Reputation: 759

You can use this pattern

\(?\d{3,3}\)?-\d{3,3}-\d{4,4}

Upvotes: 0

user2408578
user2408578

Reputation: 464

if javascript is ok can go with

<script type="text/javascript">
function matchClick() {
  var re = new RegExp("Your regex here");
  if (document.formname.phone.value.match(re)) {
     alert("Ok");
     return true;
  } else {
     alert("Not ok");
     return false;
  }
} 
</script>

call this function onsubmit of form or onblur of textbox

If you have doubt about your regex you can validate it at http://www.regular-expressions.info/javascriptexample.html

Upvotes: 0

Related Questions