1

I am making a phone number validator and all numbers should start with 168 and then followed by 9 digits 123456789.In total the phone number should only have 12 digits.

I have tried this

$phoneNumber = '168921500789';
    if( preg_match( "/^\168[0-9]{9}$/", $phoneNumber ) ){
  echo "Valid number";
} else {
  echo "Invalid number";
}

When i run the script,the number is not valid.How can i make the script take only 12 digits that must start with 168?.

Majid
  • 654
  • 2
  • 7
  • 28
  • 1
    I'm not sure about phone number validation. You can test wether it matches a pattern but this does not prevent from entering a wrong number anyways. – Daniel W. Aug 25 '14 at 12:28

3 Answers3

7

Your RegEx is wrong, there's an useless backslash before the 1. Correct:

/^168[0-9]{9}$/

Full code:

$phoneNumber = '168921500789';
if( preg_match( "/^168[0-9]{9}$/", $phoneNumber ) ){
  echo "Valid number";
} else {
  echo "Invalid number";
}
idmean
  • 14,540
  • 9
  • 54
  • 83
3

You had to remove 1 slash:

$phoneNumber = '168921500789';
    if( preg_match( "/^168[0-9]{9}$/", $phoneNumber ) ){
  echo "Valid number";
} else {
  echo "Invalid number";
}
sridesmet
  • 875
  • 9
  • 19
1

we using like this, with referred this link

public function validatePhoneNumber($number){
 $formats = array(
    '###-###-####', '####-###-###',
    '(###) ###-###','####-####-####',
    '##-###-####-####','####-####','###-###-###',
    '#####-###-###', '##########', '#########',
    '# ### #####', '#-### #####'
 );

 $format = trim(preg_replace('/[0-9]/', '#', $number));
 return (in_array($format, $formats)) ? true : false;
}
Community
  • 1
  • 1
Punitha Subramani
  • 1,467
  • 1
  • 8
  • 6
  • Be careful. It is not universal validator. It does not handle variants starting with `00` or `+` sign. – mikep Nov 23 '17 at 11:24