Since the current woeful state of HTML Forms does not support anything like VC++ or Visual Basic's input masking, here are three functions I wrote out of necessity for dealing with user phone numbers. But I think the principles can be used for many text box inputs. Just cook them a bit and you get the idea :-)
Please note: what follows is pretty basic material. My point is not to be a bore, but only to instruct those that may not be aware of PHP's capibilities (which I myself am still learning).
Basically, when checking phone numbers that are input from the user, I first "strip" them of all extraneous characters:
/* -----------------------------------------------------------------
Strip the given phone number of anything that is not a number,
e.g., ( ) - [spaces] etc.
--------------------------------------------------------------- */
function StripPhoneNum($phone_num)
{
$len = strlen($phone_num); // assume "(412) 863-0000"
for ($i = 0; $i < $len; $i++) // munch thru phone num
{
$a = $phone_num[$i];
if ( ($a < "0") || ($a > "9") ) // if not a number, delete char
$striped_phone_num .= "";
else
$striped_phone_num .= $phone_num[$i];
}
return $striped_phone_num;
}
. . . Next I check the stripped phone number for validity :
/* -----------------------------------------------------------------
Check the given "stripped" phone number for validity.
If Ok, return -1. Otherwise, return the phone number (bad) length.
--------------------------------------------------------------- */
function CheckPhoneNum($phone_num)
{
$len = strlen($phone_num);
if ($len != 10) // e.g. "4128630000"
return $len;
else
return -1;
}
. . . At this point, you could warn your user with an error message, something like
<? echo "Bad phone number $phone_num detected. Please re-enter!"; ?>
. . . Finally, when I want to restore what the user is accustomed to looking
at, I call this function :
/* -----------------------------------------------------------------
Restore dashes to valid (10 digit) phone number
Check to make sure number is valid first.
--------------------------------------------------------------- */
function ReformatPhoneNum($phone_num)
{
$len = CheckPhoneNum($phone_num);
if ($len != -1)
return $phone_num;
$len = strlen($phone_num);
for ($i = 0; $i < $len; $i++)
{
$formatted_phone_num .= $phone_num[$i];
if ( ($i == 2) || ($i == 5) )
$formatted_phone_num .= "-"; // append the dash char
}
return trim($formatted_phone_num);
}
So the striped "4128630000" reappears as ""412-863-0000" which is much more pleasing to the eyes. True, the original "(412)" is now "412-" but that's not too bad to look at considering.
I don't mean to preach here, but too many software weenies out there seem to forget that the customer is king. So don't let a little bit of programming get in the way of treating them just like that. Otherwise, they may not come back to your website and all of the above would be elementary :-)
Comments on my "primitive" style of coding are welcomed!