Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mobile number validation pattern in PHP

Tags:

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);
}
like image 534
sanzuu Avatar asked Mar 09 '16 13:03

sanzuu


2 Answers

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)
like image 141
Panda Avatar answered Oct 03 '22 03:10

Panda


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}/';
like image 23
Rafael Xavier Avatar answered Oct 03 '22 03:10

Rafael Xavier