Forum Moderators: coopster

Message Too Old, No Replies

Phone number validation problem

         

cookie2

1:58 am on Apr 8, 2006 (gmt 0)

10+ Year Member



Okay, I'm officially stuck. ;)

I'm trying to check the validity of multiple telephone numbers (home, work, cell, etc) submitted on a form. They are being passed okay as I can print them before running through the validation function. What I have is:

$phone = $_POST['telephone'];
$phonehome = $_POST['hometele'];
$phonework = $_POST['worktele'];
$phonecell = $_POST['cell'];
$phoneemer = $_POST['emergencyphone'];
$phonevol = $_POST['volunteerphone'];
function getUSPhone($var) {
$US_PHONE_PREG ="/^(?:\+?1[\-\s]?)?(\(\d{3}\)¦\d{3})[\-\s\.]?"; //area code
$US_PHONE_PREG.="(\d{3})[\-\.]?(\d{4})"; // seven digits
$US_PHONE_PREG.="(?:\s?x¦\s¦\s?ext(?:\.¦\s)?)?(\d*)?$/"; // any extension
if (!preg_match($US_PHONE_PREG,$var,$match)) {
return false;
} else {
if (substr($match[1],0,1) == "(") {
$tmp=$match[1];
} else {
$tmp=$match[1];
}
$tmp.="-".$match[2]."-".$match[3];
if ($match[4] <> '') $tmp.=" x".$match[4];
return $tmp;
}
}

Then I call the function for each as in:

if (!($phone = getUSPhone($phone))) {
$errors[] = "Illegal characters in Telephone Number";
}
if (!($phone = getUSPhone($phonehome))) {
$errors[] = "Illegal characters in Parent Home Telephone Number";
}

etc etc

Works okay when the phone number is filled in but I can't seem to get it not throw an error on an empty non-required field like work phone ($phonework). I've tried many combinations, the latest being:

if (!empty($phonework)) {
if (!($phone = getUSPhone($phonework))); {
$errors[] = "Illegal characters in Parent Work Telephone Number";
}
}

But that still doesn't work as the function gets called and the error message comes up on an empty variable.

What am I missing to get this to work right?

coopster

11:26 am on Apr 8, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



If the field is indeed empty then this code should work:
if (!empty($phonework)) { 
if (!($phone = getUSPhone($phonework))); {
$errors[] = "Illegal characters in Parent Work Telephone Number";
}
}

On the required fields, you may want to check that first, before passing it to the function:
if (empty($phone) ¦¦ !$phone = getUSPhone($phone)) { 
$errors[] = "Illegal characters in Telephone Number";
}

Now we are saying "If $phone is empty OR doesn't match our valid phone number edit" set an error. It will evaluate the first edit as TRUE and not even worry about getting to the second edit which is your function.

Don't forget that the forum breaks the pipe symbol so if you copy/paste you will have to rekey those characters in your editor.