sanzuu
sanzuu

Reputation: 192

Mobile number validation pattern in PHP

I am unable to write the exact pattern for 10 digit mobile number (as 1234567890 format) in PHP . email validation is working.

here is the code:

function validate_email($email)
{
return eregi("^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]    {2,6}$", $email);
}

function validate_mobile($mobile)
{
  return eregi("/^[0-9]*$/", $mobile);
}

Upvotes: 9

Views: 120792

Answers (4)

Long jumper
Long jumper

Reputation: 1

For any mobile number including country code, to check if valid or not simply use

filter_var($mobilevariable, FILTER_SANITIZE_NUM_INT);

do this within a function and call function name($mobilevariable). Here, + sign will be accepted, ie any country code. No need for preg_match or preg_match_all()

Upvotes: 0

Nanhe Kumar
Nanhe Kumar

Reputation: 16307

For India : All mobile numbers in India start with 9, 8, 7 or 6 which is based on GSM, WCDMA and LTE technologies.

function validate_mobile($mobile)
{
    return preg_match('/^[6-9]\d{9}$/', $mobile);
}

if(validate_mobile(6428232817)){
    echo "Yes";
}else{
    echo "No";
}

// Output will Yes

Upvotes: 2

Rafael Xavier
Rafael Xavier

Reputation: 1073

You can use this regex below to validate a mobile phone number.

\+ Require a + (plus signal) before the number
[0-9]{2} is requiring two numeric digits before the next
[0-9]{10} ten digits at the end.
/s Ignores whitespace and break rows.

$pattern = '/\+[0-9]{2}+[0-9]{10}/s';

OR for you it could be:

$pattern = '/[0-9]{10}/s';

If your input text won't have break rows or whitespaces you can simply remove the 's' at the end of our regex, and it will be like this:

$pattern = '/[0-9]{10}/';

Upvotes: 2

Panda
Panda

Reputation: 6896

Mobile Number Validation

You can preg_match() to validate 10-digit mobile numbers:

preg_match('/^[0-9]{10}+$/', $mobile)

To call it in a function:

function validate_mobile($mobile)
{
    return preg_match('/^[0-9]{10}+$/', $mobile);
}

Email Validation

You can use filter_var() with FILTER_VALIDATE_EMAIL to validate emails:

$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $emailErr = "Invalid email format"; 
}

To call it in a function:

function validate_email($email)
{
    return filter_var($email, FILTER_VALIDATE_EMAIL);
}

However, filter_var will return filtered value on success and false on failure.

More information at http://www.w3schools.com/php/php_form_url_email.asp.

Alternatively, you can also use preg_match() for email, the pattern is below:

preg_match('/^[A-z0-9_\-]+[@][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z.]{2,4}$/', $email)

Upvotes: 32

Related Questions