This is another question about a previous question I had asked yesterday. I want user to be allowed to type US phone numbers in the following formats.
(800)-555-121
if javascript is ok can go with
<script type="text/javascript">
function matchClick() {
var re = new RegExp("Your regex here");
if (document.formname.phone.value.match(re)) {
alert("Ok");
return true;
} else {
alert("Not ok");
return false;
}
}
</script>
call this function onsubmit of form or onblur of textbox
If you have doubt about your regex you can validate it at http://www.regular-expressions.info/javascriptexample.html
You can use this pattern
\(?\d{3,3}\)?-\d{3,3}-\d{4,4}
This function validate a phone number, return true if it validate and false if invalid. This function very simple i was wrote to.
/**
* @param $number
*
* @return bool
*/
function validatePhoneNumber($number) {
$formats = [
'###-###-####', '####-###-###',
'(###) ###-###', '####-####-####',
'##-###-####-####', '####-####', '###-###-###',
'#####-###-###', '##########', '#########',
'# ### #####', '#-### #####'
];
return in_array(
trim(preg_replace('/[0-9]/', '#', $number)),
$formats
);
}
Try this,
<?php
$t='/\(?[2-9][0-8][0-9]\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}/';
$arr=preg_match($t,'(800)-555-1212',$mat);
$arr=preg_match($t,'800-555-1212',$mat);
print_r($mat);
?>
Tested here
Re: Rohan Kumar's solution
<?php
$t='/\(?[2-9][0-8][0-9]\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}/';
$arr=preg_match($t,'(800)-555-1212',$mat);
$arr=preg_match($t,'800-555-1212',$mat);
print_r($mat);
?>
It does address the issue of fake phone numbers such as 800-123-2222. Real phone numbers have a first digit of at least "2". While the other solutions do the format correctly, they don't address the issue of people putting in phone numbers like 800-000-1234, which would be correct in the other solutions provided.