php 以php形式验证手机号码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11786411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:05:32  来源:igfitidea点击:

Validate Mobile number in php form

phpmysqlformsmobile

提问by user1567321

I want to validate mobile number of 10 digits and also add a prefix of 0 when I enter into the database.

我想验证10位数的手机号码,并在进入数据库时​​添加前缀0。

<?php

include ('database_connection.php');

$citystate = $_POST['citystate'];
$serviceprovider = $_POST['serviceprovider'];
$accept = $_POST['accept'];
if (isset($_POST['formsubmitted'])) {
    $error = array(); //Declare An Array to store any error message 

    if (isset($_POST['checkbox'])) {
        $mumbai = (in_array("mumbai", $_POST['checkbox']) ? 1 : 0);
        $pune = (in_array("pune", $_POST['checkbox']) ? 1 : 0);
        $banglore = (in_array("banglore", $_POST['checkbox']) ? 1 : 0);
        $mysore = (in_array("mysore", $_POST['checkbox']) ? 1 : 0);
    }

    if ($mumbai + $pune + $banglore + $mysore == 0) {
        $error[] = 'Please check atleast one SMS center';
    }

    if ($accept != 1) {
        $error[] = 'Please check terms ';
    }

    if (empty($_POST['mobileno'])) {//if no name has been supplied 
        $error[] = 'Please Enter a Mobile Number '; //add to array "error"
    }
    if (empty($_POST['mobileno'])) {//if no name has been supplied 
        $error[] = 'Please Enter a Mobile Number '; //add to array "error"
    } else {

        $mobile = $_POST['mobileno']; //else assign it a variable

        /* if( preg_match("^[0-9]{10}", $mobile) ){

          }

          else {

          $error[] = 'Your Mobile No is invalid  ';
          } */
    }
    if (empty($_POST['fname'])) {//if no name has been supplied 
        $error[] = 'Please Enter a First name '; //add to array "error"
    } else {
        $fname = $_POST['fname']; //else assign it a variable
    }

    if (empty($_POST['lname'])) {//if no name has been supplied 
        $error[] = 'Please Enter a Last name '; //add to array "error"
    } else {
        $lname = $_POST['lname']; //else assign it a variable
    }
    if (empty($_POST['email'])) {
        $error[] = 'Please Enter your Email ';
    } else {
        if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['email'])) {
            //regular expression for email validation
            $email = $_POST['email'];
        } else {
            $error[] = 'Your EMail Address is invalid  ';
        }
    }


    if (empty($_POST['passwd1'])) {
        $error[] = 'Please Enter Your Password ';
    } else {
        $password = $_POST['passwd1'];
    }
    if (empty($_POST['passwd2'])) {
        $error[] = 'Please Verify Your Password ';
    } else {
        $password = $_POST['passwd2'];
    }
    if ($_POST["passwd1"] != $_POST["passwd2"]) {
        $error[] = 'Password does not match';
    }

    if (empty($error)) { //send to Database if there's no error ' //If everything's OK...
        // Make sure the mobile no is available:
        $query_verify_mobileno = "SELECT * FROM userdtls WHERE mobileno = '$mobile'";
        $result_verify_mobileno = mysqli_query($dbc, $query_verify_mobileno);
        if (!$result_verify_mobileno) {//if the Query Failed ,similar to if($result_verify_mobileno==false)
            echo ' Database Error Occured ';
        }

        if (mysqli_num_rows($result_verify_mobileno) == 0) { // IF no previous user is using this number .
            // Create a unique  activation code:
            //$activation = md5(uniqid(rand(), true));
            $query_insert_user = "INSERT INTO userdtls ( mobileno, serviceprovider, pass,  fname, lname, email, citystate, MUM, PUN, BNG, MYS ) VALUES ( '" . $mobile . "', '" . $serviceprovider . "', '" . $password . "', '" . $fname . "', '" . $lname . "', '" . $email . "', '" . $citystate . "','" . $mumbai . "', '" . $pune . "', '" . $banglore . "', '" . $mysore . "'  )";
        }
    }
}

Now I get stuck in mobile number validation. I tried using regular expressions.

现在我陷入了手机号码验证的困境。我尝试使用正则表达式。

What I want to do is add a 10 digit phone number and make sure it is only digits or else give error and while entering the number to database I want to add a prefix to the mobile number of 0 so it should be like 0and10digitnumber

我想要做的是添加一个 10 位数的电话号码,并确保它只是数字,否则会出错,在将号码输入数据库时​​,我想为 0 的手机号码添加前缀,因此它应该像 0and10digitnumber

采纳答案by Oussama

Try something like this :

尝试这样的事情:

$phoneNumber = $_POST['mobileno'];

if(!empty($phoneNumber)) // phone number is not empty
{
    if(preg_match('/^\d{10}$/',$phoneNumber)) // phone number is valid
    {
      $phoneNumber = '0' . $phoneNumber;

      // your other code here
    }
    else // phone number is not valid
    {
      echo 'Phone number invalid !';
    }
}
else // phone number is empty
{
  echo 'You must provid a phone number !';
}

回答by Pawe? Tomkiel

Probably the most efficient and well-readable form would be to use the libphonenumberlibrary from Google. PHP forkis available on GitHub. It can help you not only to validate number itself, but you can check country code with it or even know if some number is valid for specific country(this lib knows which number prefixes are valid for many countries). For example: 07700 900064is valid GB number, but 09700 900064is not, even if they have same length.

可能最有效和最易读的形式是使用Google的libphonenumber库。PHP叉可以在GitHub上。它不仅可以帮助您验证号码本身,还可以使用它检查国家/地区代码,甚至可以知道某个号码是否对特定国家/地区有效(此库知道哪些号码前缀对许多国家/地区有效)。例如:07700 900064是有效的 GB 数,但09700 900064不是,即使它们具有相同的长度

Here's how I would validate mobile phone number in your app:

以下是我在您的应用中验证手机号码的方法:

$phoneNumber = $_POST['mobileno'];
$countryCode="GB";

if (!empty($phoneNumber)) { // phone number is not empty
    $phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
    $mobileNumberProto = $phoneUtil->parse($phoneNumber, $countryCode);
    if ($phoneUtil->isValidNumber($mobileNumberProto)) { // phone number is valid
        //here you know that number is valid, let's try to format it without country code but with 0 at the beginning (national number format)
        $phoneNumber = $mobileNumberProto->format($mobileNumberProto, PhoneNumberFormat::NATIONAL);
    } else {
        $error[] = 'Phone number not valid!';
    }
} else {
    $error[] = 'You must provide a phone number!';
}

$countryCodeis two chars ISO 3166-1code. You can check it for your country on Wikipedia.

$countryCode是两个字符的ISO 3166-1代码。您可以在Wikipedia上查看您所在国家/地区的信息。

回答by Ravinder Payal

For Indian Mobile Numbers it will be most easiest

对于印度手机号码,这将是最简单的

if(is_numeric($num)){
if($num=>1000000000 and $num=<9999999999){
$num="0".$num;
}
else{
echo "Invalid Mobile Number";
}
}
else{
echo "Hey Buddy mobile numbers are always in digits";
}

This idea strike me because of willingness of finding easy and some short of mind because the number(1000000000 ) is lowest numerical value(10 digits) and the number (9999999999) is highest numerical value that can be used as mobile number in India. And one more thing code will run more faster than other solutions.

这个想法让我印象深刻,因为它很容易找到,而且有些头脑空白,因为数字(1000000000)是最低的数值(10位数字),而数字(9999999999)是可用作印度手机号码的最高数值。还有一件事代码将比其他解决方案运行得更快。

回答by pravin tripathi

if(!ereg("^[7-9]{1}[0-9]{9}$", $mob)) { return false; }

回答by Abhishek Bhardwaj

Improving pravin tripathi's answer:

改进 pravin tripathi 的回答:

if(!ereg("^[7-9]{1}[0-9]{9}$", $mob)) { return false; }

if(!ereg("^[7-9]{1}[0-9]{9}$", $mob)) { return false; }

since ereg() is deprecated, you could use

由于 ereg() 已弃用,您可以使用

preg_match("/^[7-9]{1}[0-9]{9}$/i", $mobile_no)

This will help you validate a mobile number from India, since they are 10 digits and start with 7, 8 or 9 as of today. You could always change the pattern if new digits get introduced.

这将帮助您验证来自印度的手机号码,因为它们是 10 位数字,从今天开始以 7、8 或 9 开头。如果引入新数字,您可以随时更改模式。

回答by lead_brogrammer

Have you tried a regular expression like:

您是否尝试过以下正则表达式:

if( !preg_match("/^([0-1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i", $phone) ) {
   echo 'Please enter a valid phone number';
}