regex phone number validation with PHP

前端 未结 5 1143
孤独总比滥情好
孤独总比滥情好 2021-01-17 01:33

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-121

相关标签:
5条回答
  • 2021-01-17 01:46

    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

    0 讨论(0)
  • 2021-01-17 01:46

    You can use this pattern

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

    0 讨论(0)
  • 2021-01-17 01:54

    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
            );
        }
    
    0 讨论(0)
  • 2021-01-17 01:57

    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

    0 讨论(0)
  • 2021-01-17 02:02

    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.

    0 讨论(0)
提交回复
热议问题