I want to display an error message if the number doesn't match any number with hyphen, plus sign, space or brackets. No numbers either.
For example:
(012) 123 4567
(012)-123-4567
012-345-6789
123 123 1234
+12 23 213 3456
The above examples all work with this expression:
if (!preg_match("/^[0-9\-]|[\+0-9]|[0-9\s]|[0-9()]*$/", $_POST['tel'])) {
$telErr = "Invalid contact number";
}
But it allows letters, which I do not want.
Example:
+00000000a
The above example is accepted by the expression I have.
Please can someone help me with this.
Better regular expression is:
"/^[\+0-9\-\(\)\s]*$/"
This expression'll accept +5number, 5number
"'^(([\+]([\d]{2,}))([0-9\.\-\/\s]{5,})|([0-9\.\-\/\s]{5,}))*$'"
I first cleanup the string a bit (that avoids useless matches):
$input = preg_replace('/[^0-9+\(\)-]/', '', $_POST['tel']);
I than match an american number +1 (xxx) xxx-xxxx;
if(preg_match('/^(\+1|001)?\(?([0-9]{3})\)?([ .-]?)([0-9]{3})([ .-]?)([0-9]{4})/',$input))
$result = "match: USA";
else $result = "no match";
this allows for quite some input configurations - only your last number would not match (if I'd not do the cleanup first, not because of the international code which is matched, but because of the split in the area-code) all the others go also without cleanup.