Oct 31st, 2009, 10:51 AM
Hey Invectus,
Sure, no problem! Users can enter the characters in any old way, so you need to think up all the different scenarios.
I'd approach it like this:
1. Strip out all non-numeric characters
2. Depending on the length of the string, do different things. If it's exactly 10 characters, you know the user conscientiously entered the area code + full phone number. If it's 11, they entered the long distance "1" as well. If it's only 7 chars, they omitted the area code.
If it's something else...??? Who knows! Users will ALWAYS find a way to screw it up, so we need to take care of those cases too.
Here's some code you can enter into your Submission Pre-Parser rule:
That will take care of those scenarios I mentioned, and if the phone number is a non-standard length, it'll just leave it alone. You WILL need to update the $_POST["phone"] key with whatever your phone number field is called.
Hope this helps!
- Ben
Sure, no problem! Users can enter the characters in any old way, so you need to think up all the different scenarios.
I'd approach it like this:
1. Strip out all non-numeric characters
2. Depending on the length of the string, do different things. If it's exactly 10 characters, you know the user conscientiously entered the area code + full phone number. If it's 11, they entered the long distance "1" as well. If it's only 7 chars, they omitted the area code.
If it's something else...??? Who knows! Users will ALWAYS find a way to screw it up, so we need to take care of those cases too.
Here's some code you can enter into your Submission Pre-Parser rule:
PHP Code:
$phone = $_POST["phone"];
$phone = preg_replace("/\D/", "", $phone);
$num_chars = strlen($phone);
$formatted_phone_num = "";
if ($num_chars == 10) {
$formatted_phone_num = "(" . substr($phone, 0, 3) . ") " . substr($phone, 3, 3) . "-" . substr($phone, 6, 4);
} else if ($num_chars == 11) {
$formatted_phone_num = substr($phone, 0, 1) . " (" . substr($phone, 1, 3) . ") " . substr($phone, 4, 3) . "-" . substr($phone, 7, 4);
} else if ($num_chars == 7) {
$formatted_phone_num = substr($phone, 0, 3) . "-" . substr($phone, 3, 4);
} else {
$formatted_phone_num = $phone;
}
$_POST["phone"] = $formatted_phone_num;
That will take care of those scenarios I mentioned, and if the phone number is a non-standard length, it'll just leave it alone. You WILL need to update the $_POST["phone"] key with whatever your phone number field is called.
Hope this helps!
- Ben