简体   繁体   中英

PHP phone number validation

I am trying to display error messages to user if they entered a wrong uk phone number format or not a number, but the error messages not working.

HTML

<input type="text" name="phone" class="form-control" value="<?php echo $phone;?>" placeholder="Mobile Number "> 


<span class="error"><?php echo $phoneErr;?></span>

PHP

    $phoneErr = "";  
    $phone = "";

  if (empty($_POST["phone"])) {
     $phone = "";
   } else if(!preg_match( $phone, '/^(?:\(\+?44\)\s?|\+?44 ?)?(?:0|\(0\))?\s?(?:(?:1\d{3}|7[1-9]\d{2}|20\s?[78])\s?\d\s?\d{2}[ -]?\d{3}|2\d{2}\s?\d{3}[ -]?\d{4}) $/')) 
   {
       $phoneErr = "Invalid phone number"; 
   }else {
       $phone = test_input($_POST["phone"]);
   }
test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}

If it's not a number nothing will be inserted to the database, but if I typed a number 9223372036854775807 will be inserted, this value is not the one I entered. I have done some researches, I think this value means invalid string.

Other parts of my form are working fine only the phone number not working well, I am not sure why.

First of all: your regular expression (even purged by final space) doesn't match . 不匹配。

You don't show how you insert values in database, but if above code is for checking the phone number, it's a mystery how any phone number can be inserted, unless you insert $_POST['phone'] . But why you insert $_POST['phone'] if you before try to convert it in $phone ?

I say “try”, because in fact the line $phone = test_input($_POST["phone"]) never happens.

If $_POST['phone'] is empty, you set $phone to empty string (this in unnecessary: $phone is already an empty string, but this is not a problem), otherwise you test your regular expression, but you test it on $phone (an empty string), not on $_POST['phone'] ; in addition, you invert preg_match arguments, so in fact you test if an empty pattern matches string /^(?:\\(\\+?44\\)\\s?|\\ ... .

You have to rewrite your check routine in something like this:

$phoneErr = False;  
$phone    = "";

if( ! empty( $_POST["phone"] ) ) 
{
    $pattern = '/^(?:\(\+?44\)\s?|\+?44 ?)?(?:0|\(0\))?\s?(?:(?:1\d{3}|7[1-9]\d{2}|20\s?[78])\s?\d\s?\d{2}[ -]?\d{3}|2\d{2}\s?\d{3}[ -]?\d{4})$/';
    if( !preg_match( $pattern, $phone ) )
    {
        $phoneErr = "Invalid phone number"; 
    }
    else 
    {
        $phone = test_input($_POST["phone"]);
    }
}

(...)

if( $phoneErr )
{
    // Your error routine here
}
elseif( $phone )
{
    // Insert $phone (not $_POST['phone']) to database
}

Regarding your regular expression, check it with more than one UK valid numbers on regex101.com before using it. As alternative, you can try the regular expressions suggested in question cited in comments.

Solved

<?php
 require_once('connect.php');
    if(isset($_POST['submit']))
    {
        $name= strip_tags($_POST['name']);  
        $phone = strip_tags($_POST['phone']);   

        if($name=="")   {
            $error[] = "Please enter name.";    
        }
        else if(!preg_match('/^[a-zA-Z ]*$/', $name)) 
        {
            // check if name only contains letters and whitespace
           $error[] = "Only letters and white space allowed for name"; 
        }

    else
    {
        if( !empty($phone) ) 
        {
            $pattern = '/^(?:\(\+?44\)\s?|\+?44 ?)?(?:0|\(0\))?\s?(?:(?:1\d{3}|7[1-9]\d{2}|20\s?[78])\s?\d\s?\d{2}[ -]?\d{3}|2\d{2}\s?\d{3}[ -]?\d{4})$/';
            if(!preg_match($pattern, $phone)){
                $error[] = 'Please enter a valid phone number!';
            }else{


         try {
             $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
             $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);     

             $stmt =$conn->prepare( "INSERT INTO contact (name,phone)
                  VALUES( :name, :phone)");

              $stmt->bindparam(':name', $name); 
              $stmt->bindparam(':phone', $phone);   
              $stmt->execute(); 

            }catch(PDOException $e) {
             echo "Error: " . $e->getMessage();
             die();
            }

            }
        }
        }
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM