Mobile number validation pattern in PHP

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

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)

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

Tags:

Php