sanzuu sanzuu - 1 month ago 14
PHP Question

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

Answer

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)
Comments