开发者

looking to validate US phone number w/ area code

I'm working on a function to validate a US phone number submitted by a user, which can be submitted in any of the popular number formats people usually use开发者_运维知识库. My code so far is as follows:

$number = '123-456-7890';

function validate_telephone_number($number) {
    $formats = array(
        '###-###-####',
        '(###)###-###',
        '(###) ###-###',
        '##########'
    );

    $number = trim(preg_replace('[0-9]', '#', $number));

    if (in_array($number, $formats)) {
        return true;
    } else {
        return false;
    }
}

First off, this code does not seem to be working, and returns false on all submitted numbers. I can't seem to find my error.

Secondly, I'm looking for an easy way to only allow phone numbers from an array of specific allowed area codes. Any ideas?


For your first question:

preg_replace('/[0-9]/', '#', $number)

or '/\d/'


For the second question this may help you:

$areaCode = substr(preg_replace('/[^\d]/', '', $number),0 , 3);

This will give you the first 3 digits in the number by discarding all other characters.

I'm not familiar with the US area codes format so I cannot help you more with this one.


Bonus:

if (in_array($number, $formats)) {
    return true;
} else {
    return false;
}

is equivalent to

return in_array($number, $formats);

As a matter of fact any statement of the form

if(<expression>){
    return true;
}
else{
    return false;
}

can be written as return (bool) <expr>;, but in this case in_array will always return a Boolean so (bool) is not needed.


Your code does not check for well formatted but invalid numbers - for example, no area code starts with 0 or 1 in the US, so this could be checked. Also, your formats do not allow for country code inclusion - +15551234567 would be rejected, for example.

If you don't care about the formatting and just want to validate if the digits in the input amount to a valid US phone number, you could use something like this:

$clean_number = preg_replace("/[^0-9]/", '', $number);
$valid = preg_match("/^(\+?1)?[2-9][0-9]{9}$/", $clean_number);

Of course, this will also accept "foo 5555555555 bar" as a valid number - if you want to disallow that, make the preg_replace more restrictive (e.g, remove only brackets, spaces and dashes).


If you prefer to do this without maintaining a lot of code, you an check out this API that validates a US number and provides several formats for the number https://www.mashape.com/parsify/format


Look here for a code project that has a function for validating phone numbers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜