Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

codeigniter form validation with phone numbers

Tags:

codeigniter

What's a good way to validate phone numbers being input in codeigniter?

It's my first time writing an app, and I don't really understand regex at all.

Is it easier to have three input fields for the phone number?

like image 994
Kevin Brown Avatar asked Dec 20 '09 22:12

Kevin Brown


3 Answers

Here's a cool regex I found out on the web. It validates a number in almost any US format and converts it to (xxx) xxx-xxxx. I think it's great because then people can enter any 10 digit US phone number using whatever format they are used to using and you get a correctly formatted number out of it.

Here's the whole function you can drop into your MY_form_validation class. I wanted my form to allow empty fields so you'll have to alter it if you want to force a value.

function valid_phone_number_or_empty($value)
{
    $value = trim($value);
    if ($value == '') {
        return TRUE;
    }
    else
    {
        if (preg_match('/^\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}$/', $value))
        {
            return preg_replace('/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/', '($1) $2-$3', $value);
        }
        else
        {
            return FALSE;
        }
    }
}
like image 111
Dana Avatar answered Nov 08 '22 02:11

Dana


The best way is not to validate phone numbers at all, unless you're absolutley 100% positive that you're only dealing with phone numbers in the US or at least North America. As soon as you allow phone numbers from Europe I don't think there's a regex which covers all possibilities.

like image 29
Fant Avatar answered Nov 08 '22 02:11

Fant


strip out the non-digits with this:

$justNumbers = preg_replace( '/\D/', $_POST[ 'phone_num' ] );

and see if there are enough characters!

$numRequired = 7; // make your constraints here
if( strlen( $justNumbers ) < $numRequired ){ /* ... naughty naughty ... */ }

this is loose, of course, but will work for international numbers as well (as all it's really doing is seeing if there are over 7 numbers in the input).

just change the number of required digits according to your specifications.

like image 3
Dan Beam Avatar answered Nov 08 '22 02:11

Dan Beam