0

This is my code:

I never set validation for phone number field, I try "/^([0-9]{3})-[0-9]{3}-[0-9]{4}$/" this type of code for validation, I enter text in the phone number field, they accept in backend

what can I do? for set validation for phone number field.

<!DOCTYPE HTML>  
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
.error {color: #FF0000;} 
</style>
</head>
<body>  

<?php
$nameErr = $phoneErr = "";
$name =  $phone = "";

$error = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field

     $name = htmlspecialchars($_REQUEST['name']);
     $phone = htmlspecialchars($_REQUEST['phone']); 


    if (empty($name)) {
        $nameErr = "* Name is required";
      $error = 1;
        // echo "Name is empty";
    }

    if (empty($phone)) {
        // echo "phone is empty";
        $phoneErr = "* Phone is required";
        $error = 1;
    }

}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
    <h1>Login Form</h1>
  Name: <input type="text" name="name" onkeydown="return alphaOnly(event);" value="<?php echo $name ?>">
   <span class="error"> <?php echo $nameErr?></span>  
  <br></br>

  Phone: <input type="text" name="phone" value="<?php echo $phone ?>">
    <span class="error"> <?php echo $phoneErr?></span> 
   <br><br>

  <input type="submit"> 

  <br><br>

</form>

</body>
</html>

I need to validate phone number in PHP, but the example do not work. How can I set validation for mobile number

Vicky Mahale
  • 1,209
  • 11
  • 18
  • 3
    Think about it **twice**.... do you "really" need to validate phone numbers? – B001ᛦ Nov 14 '17 at 11:26
  • Yes, you should validate phone numbers of course if you rely on them lets say for verification or support purposes. Also there are quite a few formats for phone numbers, keep that in mind. Just checking for integers is not enough. – Manuel Mannhardt Nov 14 '17 at 11:28
  • I enter text in the phone number field, they also submit in backend – Vicky Mahale Nov 14 '17 at 11:29
  • 1
    The only way of *validating* a phone number is to call them and verify that they are valid (connected and belonging to the user that submitted them). – Morpheu5 Nov 14 '17 at 11:29
  • 1
    Its the exact same thing as validating email. Everyone just checks if the email has a valid format, no one checks if it actually exists. I dont see your point there. – Manuel Mannhardt Nov 14 '17 at 11:30
  • @Morpheu5 _Yes, you should validate phone numbers of course if you rely on them..._ what if user put in the **right** format but the **wrong** number ? ;) – B001ᛦ Nov 14 '17 at 11:30
  • Come on! call them? we talking about `php` validating – Pedram Nov 14 '17 at 11:30
  • @B001 wrong poster :) I agree, see my actual comment :) – Morpheu5 Nov 14 '17 at 11:30
  • Same to you @B001, you could say the exact same thing for email addresses. – Manuel Mannhardt Nov 14 '17 at 11:30
  • @ManuelMannhardt exactly the same.. this is why your commment got +1 from me – B001ᛦ Nov 14 '17 at 11:31
  • Ok, so you never actually validate your email addresses? – Manuel Mannhardt Nov 14 '17 at 11:32
  • @vickymahale are you talking about `mobile phone number` ? which country? – Pedram Nov 14 '17 at 11:33
  • 1
    The point is that phone numbers are just lists of digits, they don't have a particular machine-enforceable format. A "valid" phone number depends on context, whether you can, by keying in those digits from a phone in a particular network and location in the World, reach a valid user. E-mail addresses follow a specific format that, if not used, makes them invalid. That's it. – Morpheu5 Nov 14 '17 at 11:33
  • _E-mail addresses follow a specific format that, if not used, makes them invalid..._ Are you sure? Again--- what if I put in the right format but your email adress instead of mine? – B001ᛦ Nov 14 '17 at 11:34
  • @pedram, Yes I talking about Mobile/Phone number field. – Vicky Mahale Nov 14 '17 at 11:35
  • It depend to your country, number of digit and and by which number it starts @vickymahale – Pedram Nov 14 '17 at 11:37
  • 1
    @B001 Validation is not the same as verification, but you *can* validate an e-mail address against a format, you can't necessarily do that for a phone number. For example, +1-555-5324, 0015555324 would represent the exact same user when calling from within the USA, but 5555324 may not, if you are not calling from the USA. – Morpheu5 Nov 14 '17 at 11:37
  • @pedram I'm from India & mobile number should start from +91 – Vicky Mahale Nov 14 '17 at 11:40
  • Well Morpheu5, you kinda can. Just strip all braces, dashes and spaces and check its result for length and numbers. As you said, validation and verification are two different things and one big reason why you should always validate is UX. Tell the user that he has typed in something wrong! – Manuel Mannhardt Nov 14 '17 at 11:44
  • Well, and you only want validate India mobile number, right? @vickymahale or international? – Pedram Nov 14 '17 at 11:44
  • Wow this has gone sideways... OP I can't even see that you have tried the regex in the code you posted. The regex should not accept letters. Try it here; https://regex101.com/r/Ahw5Sg/1 – Andreas Nov 14 '17 at 11:45
  • @pedram, yes only for india – Vicky Mahale Nov 14 '17 at 12:03
  • @vickymahale you can look at the regex suggested in accepted answer here https://stackoverflow.com/questions/3813195/regular-expression-for-indian-mobile-numbers – Sanjay Nov 14 '17 at 12:07
  • Can you give us a example phone number? no problem if fake, just want to know how your user will write their phone numbers. @vickymahale – Pedram Nov 14 '17 at 12:09
  • 1
    @pedram +91- 9869123456 – Vicky Mahale Nov 14 '17 at 12:10
  • @ManuelMannhardt I can think of at least two ways in which this breaks: 1) not all phone numbers have the same length, and 2) not all area codes exist. Suppose you say the length is at least 6 digits, and there comes along someone with a very old landline with 5 digits (yes, they still exist, and they are a problem for providers all over the world). Suppose also that someone types in 1-555-4321, you strip the dashes, count the digits, you are all set to go, but 555 is a notorious fictitious area code. However, 555-1212 is a perfectly valid directory service in North America. How do you even…? – Morpheu5 Nov 14 '17 at 19:15

3 Answers3

2

Sorry to answer an old post.

However, you can check if the number exists by calling a web service. In this case, I found numverify.com, allowing to verify if a phone number exists.

After creating a free account (allows you to make 250 requests each month), you can invoke the following basic code in PHP:

// set API Access Key
$access_key = 'YOUR_ACCESS_KEY';

// set phone number
$phone_number = '14158586273';

// Initialize CURL:
$ch = curl_init('http://apilayer.net/api/validate?access_key='.$access_key.'&number='.$phone_number.'');  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Store the data:
$json = curl_exec($ch);
curl_close($ch);

// Decode JSON response:
$validationResult = json_decode($json, true);

I have no idea if this is reliable, but it worked with my phone number and even retrieved the company carrier.

davidc2p
  • 320
  • 3
  • 9
0

According to comments and example phone number that you given, this code will validating number of digits and first two numbers of your country, i just replaced + with 0, for sure they won't enter plus.

$tel = '091-9869123456';

if(preg_match("/^[0-9]{3}-[0-9]{10}$/", $tel)) {
    echo "valid";
} else {
    echo "invalid";
}

Now for more validating need to check country code:

if(substr($tel, 0, 3) == '091'){
    echo "valid";
} else {
    echo "invalid, it should start with 091";
}

Or you do this with same preg_match like this:

if(preg_match("/^[091]{3}-[0-9]{10}$/", $tel)) {
    echo "valid";
} else {
    echo "invalid";
}

Demo

Pedram
  • 15,766
  • 10
  • 44
  • 73
-1

Why do you need to validate phone number using php? You can do it using JS as shown below.

if (/^\+[-0-9]{6,20}$/.test(phoneNumber) == false) {
      alert('Wrong Phone Number format. Only numbers,+ and - are allowed. Format: \<Country Code\>\<Phone number\> Eg: +9199999999, +1-105-893-9334 etc');
    return;
} 
Pedram
  • 15,766
  • 10
  • 44
  • 73
PeeKay
  • 167
  • 2
  • 2
  • 10
  • 1
    _"Why do you need to validate phone number using `php`?"_ - For example, because JavaScript can be deactivated or changed. It is client-side code. – domsson Jan 13 '20 at 14:56