Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple RegEx changes for phone number validation

Tags:

regex

php

i have this function to check my phone number:

function isValid( $what, $data ) {

        switch( $what ) {

                // validate a phone number
                case 'phone_number':
                        $pattern = "/^[0-9-+]+$/";

                break;



                default:
                        return false;
                break;

        }
        return preg_match($pattern, $data) ? true : false;
}

i want to change that regex to accept the following: the ) ( chars like (800) and the space.

So for example this number will pass the validation, right now is not passing:

+1 (201) 223-3213

like image 316
Abude Avatar asked Dec 09 '22 21:12

Abude


2 Answers

Let us construct the regular expression step by step. Consider also that spaces are trimmed before matching.

  • at the beginning there might or might not be a + sign. This also needs to be escaped. \+?
  • then comes one or more digits, before the part with parenthesis [0-9]+ You might want to write [0-9]* if the number can begin directly with a group in parenthesis
  • then, optionally comes a group of digits in parenthesis: (\[0-9]+\)?. Suppose that only one such group is allowed
  • then comes the local phone number, hyphens also allowed: [0-9-]*
  • the final character must be a digit [0-9], hyphen is not allowed here

    ^\+?[0-9]+(\([0-9]+\))?[0-9-]*[0-9]$
    

See the result here. Trimming spaces looks like $trimmed = str_replace(' ', '', $pattern);.

like image 80
Lorlin Avatar answered Jan 31 '23 10:01

Lorlin


How about this regexp:

/^[0-9-+()\s]+$/

See it in action here

like image 31
zb226 Avatar answered Jan 31 '23 10:01

zb226