user3286430
user3286430

Reputation:

Validate phone number in php

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?.

Upvotes: 1

Views: 2917

Answers (3)

Punitha Subramani
Punitha Subramani

Reputation: 1477

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;
}

Upvotes: 1

sridesmet
sridesmet

Reputation: 895

You had to remove 1 slash:

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

Upvotes: 3

idmean
idmean

Reputation: 14905

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";
}

Upvotes: 7

Related Questions