I am currently working with validation of US phone numbers. The issue is that code below is always echoing after a valid or invalid input Please enter a valid phone number
. My basic logic of my code is that I am checking with the preg_match to see if there is match for a valid number. Example
How can I fix this or is there a better way to validate phone numbers?
Also, Is there away to echo the number formatted like this: (123)456-7890
?
PHP:
if (isset($_POST['phone'])) {
if(preg_match('/^(\({1}\d{3}\){1}|\d{3})(\s|-|.)\d{3}(\s|-|.)\d{4}$/',$phone)) {
echo ('<div id="phone_input"><span id="resultval">'.$phone.'</span></div>');
}
else {
echo '<div id="phone_input"><span id="resultval">Please enter a valid phone number</span></div>';
}
}