fisicx;10932960 wrote:Thanks jaql,
What I want to do is check the whole string for anything other than 0-9, the symbols +-() and a space. If there is an match then the error message asks the user to check their telephone number.
I could easily strip out the offending characters but I'm trying to be a little more helpful.
Suggestion please?
My suggestion would be to strip out offending characters, look at what numbers you have left (to see if the length of numbers matches the phone number format you desire (ie. if area code is present or not)).
One serious pet peeve when dealing with online forms is when a site forces an user to format something specifically. I never understood why they did this. Take the 'No Dashes or Spaces Hall of shame' site (which belongs to the brother of Jeffrey Friedl, who is the author of Mastering regular expressions) for instance. That site maintains that making it a requirement of no dashes or spaces is akin to programmer laziness (and I agree with that completely).
So back to phone numbers... why punish an user if they format it like (555) 555-5555 or 555-555-5555 or 555.555-5555, etc..? This is a sure fire way to frustrate legitimate, honest, well intentioned users.. let them format the number to their liking.. and simply look at only the numbers they leave and see if that is the length is valid or not, and base that info on whether or not the user has commited an error. Afterall, with all non-numerics stripped out, nothing stops you from reformatting it for them.
Example (based on north american number with area code):
$input = '555.246.5555'; // not the format we want, but that's ok...
$phoneNumber = preg_replace('#[^0-9]#', '', $input);
if(strlen($phoneNumber) == 10){
// valid north american formatted phone number (area code included)
// Now we can reformat this to our liking instead of being too strict with the end user
echo $phoneNumber = '(' . substr($phoneNumber, 0, 3) . ') ' . substr($phoneNumber, 3, 3) . '-' . substr($phoneNumber, -4); // Output: (555) 246-5555
} else {
// warning: improper amount of numbers used. Ask user to re-verify
}
There are far too many restrictive forms out there that don't make life easier for the user (all because the programmer wants things in a specific format, yet is not willing to do that part for the user, and instead burdens the user (which I might add risks the user abandoning the site in question and going elsewhere.. after all, who likes hassles)?