How to validate phone number with zero at the front in php? - php

I am validating phone numbers and this is my conditions,
if (!empty($phone)) {
if (!filter_var($phone, FILTER_VALIDATE_INT) || !filter_var($phone, FILTER_VALIDATE_INT) === 0 || !is_numeric($phone) || !intval($phone)) {
// Error msg
// This segment working fine but
// Its throwing error msg when I am using a mobile number starting with a zero
// Like 01234567890
} else {
if (strlen($phone) > 16 || strlen($phone) < 8) {
// Error msg
} else {
// Valid msg
}
}
} else {
// Error msg
}
I want to through error msg if someone using 8 zeros or 16 zeros and I think its working but if someone using a valid phone number which is starting with a zero, then its throwing error msg as well.
How to pass number starting with a zero but mot all zeros?

Employ the same classic lookahead technique that is commonly used for validating passwords.
Ensure that the phone is between 8 and 16 digits and has at least one non-zero.
Code: (Demo)
echo preg_match('/^(?=0*[1-9])\d{8,16}$/', $phone) ? 'Pass' : 'Fail';
Do not cast phone numbers as integers or store them as integers in a database if they can possibly start with a zero in your project.
Without regex, use an assortment of string function calls for the same effect. Demo
echo ctype_digit(ltrim($phone, '0')) && $length >= 8 && $length <= 16 ? 'Pass' : 'Fail';

Related

How to validate both greater than AND less than

I am writing validation for a book management system, and I want to make it so that if the length of the ISBN entered is either less than or greater than 13 or 10, it displays the error message, however it says that there is an unexpected '<' whenever I try the following.
if(strlen($_POST['isbndelete'] (< 13 || 10) || (> 13 || 10)))
{
$error="The length of the ISBN is incorrect.";
echo $error;
return false;
}
All help is appreciated!
Your main issue is that your condition is not valid PHP. You should read more about conditional statements syntax.
Validing ISBN length
ISBNs are either 10 or 13 characters.
So you can simply check if your string does not contain exactly 10 and does not contain 13 characters either, like this:
$len = strlen($_POST['isbndelete']);
if ($len != 10 && $len != 13) {
$error = "The length of the ISBN is incorrect.";
echo $error;
return false;
}

PHP preg_match for validating 10 digit mobile number

I am trying to validate 10 digits mobile number using PHP function preg_match. The below code does not produce any output.
Is it the regex wrong? or I am using it incorrectly.
I was expecting Hi True in the output. if it matches or Hi False if it does not match.
<?php
$value = '9987199871';
$mobileregex = "/^[1-9][0-9]{10}$/" ;
echo "Hi " . preg_match($mobileregex, $value) === 1; // #debug
?>
regex taken from https://stackoverflow.com/a/7649835/4050261
The regex you stated will match eleven digits, not ten. Since all Indian mobile numbers start with 9,8,7, or 6, we can use the following regex:
^[6-9][0-9]{9}$
Here is your code snippet updated:
$value = '9987199871';
$mobileregex = "/^[6-9][0-9]{9}$/" ;
echo "Hi " . preg_match($mobileregex, $value) === 1;
Note that the above regex is still probably far from the best we could do in terms of validation, but it is at least a start.
The following code snippet will check if the mobile number digits are within 10-15 digits including '+' at the start and followed by a non-zero first digit.
Regular expression
"/^[+]?[1-9][0-9]{9,14}$/"
Code snippet
// Validation for the mobile field.
function validateMobileNumber($mobile) {
if (!empty($mobile)) {
$isMobileNmberValid = TRUE;
$mobileDigitsLength = strlen($mobile);
if ($mobileDigitsLength < 10 || $mobileDigitsLength > 15) {
$isMobileNmberValid = FALSE;
} else {
if (!preg_match("/^[+]?[1-9][0-9]{9,14}$/", $mobile)) {
$isMobileNmberValid = FALSE;
}
}
return $isMobileNmberValid;
} else {
return false;
}
}
^ symbol of the regular expression denotes the start
[+]? ensures that a single(or zero) + symbol is allowed at the start
[1-9] make sure that the first digit will be a non zero number
[0-9]{9,14} will make sure that there is 9 to 14 digits
$ denotes the end
$mob = "9513574562";
if(preg_match("/^\d+\.?\d*$/",$mob) && strlen($mob)==10){
echo 1;
}else{
echo 0;
}
preg_match() checking it is integer or not and in strlen() it is checking no of digit in this string. If 2 condition satisfy then it is a 10 digit valid mobile no
for pakistani mobile number the regex code will be the following
^[9][2][3][0-9]{9}$

Validating lengh of a phone with PHP

I'm trying to validate the length of a phone number staying within a range. Let's say at least 9 characters but not more than 12 so I can get international phone numbers.
I tried several things but none of them work.
The option below for instance validates correctly that it has not letter, however it doesn't matter the length of the number I introduce, I always get the Error Message: "Your phone number needs to have 9-11 numbers" even if I introduce a 9, 10 or 11 eleven digits number.
Thank you so much
if (empty($_POST["cellphone"])) {
$cellphoneErr = "Cell Phone is required";
} else {
$cellphone = test_input($_POST["cellphone"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[0-9]*$/",$cellphone)) {
$cellphoneErr = "Only numbers allow";
}
elseif(strlen($_POST["cellphone"] < 9) || strlen($_POST["cellphone"] > 11)){
$cellphoneErr = "Your phone number needs to have 9-11 numbers";
}
}
Use preg_match() with quantifier {min,max}:
if (!preg_match("/^[0-9]{9,11}$/",$cellphone)) {
$cellphoneErr = "Has to be 9 to 11 numbers.";
}
elseif(strlen($_POST["cellphone"] < 9) || strlen($_POST["cellphone"] > 11)){
Should be:
elseif(strlen($_POST["cellphone"]) < 9 || strlen($_POST["cellphone"]) > 11){
Your parenthesis are wrong.

Issues with integer operations

function sendSms($toPhone,$message){
$toPhone=intval(trim($toPhone));
if(strlen($toPhone)== 8 && $toPhone{0}==9){
//sending sms
}else{
return "error";
}
}
I am trying to validate mobile numbers for sending SMS. The first line trims the phone number string and then converts it to an integer. In the if statement, I want to make sure that the number length is 8 digits and it begins with 9. This function always goes for the else even if the number is correct( 8 digits and begins with 9). What could be the issue here.
Why not regex?
$valid = preg_match('/^9[0-9]{7}$/', trim($phone));
You can remove from $toPhone all not digits
function sendSms($toPhone,$message){
$_phone = '';
for ($i = 0; $i < strlen($toPhone); $i++)
{
if (is_numeric($toPhone[$i]))
$_phone .= $toPhone[$i];
}
if(strlen($_phone)== 8 && $_phone[0]=='9'){
//sending sms
}else{
return "error";
}
}
After you converted the phone number to an integer with $toPhone=intval(trim($toPhone));,, you can't access the digits in the way you are trying with $toPhone{0}, because you operate on a number and not on a string any more.
See this isolated example:
$number = 987654321;
var_dump($number{0}); //NULL
However, substr would be capable of doing this:
$number = 987654321;
var_dump(substr($number, 0, 1)); //string(1) "9"
Converting a whole number to integer isn't a good idea anyways, because users might enter the number with spaces in between or signs like + and /. Better search for an already existing approach to validate phone numbers.
Take a look here, where the topic "validate mobile phone numbers" is covered in more detail: A comprehensive regex for phone number validation
You convert variable to integer and apparently $toPhone[0] works on strings only.
The same function without intval() works as you wanted.
function sendSms($toPhone, $message)
{
$toPhone = trim($toPhone);
if(strlen($toPhone) == 8 && $toPhone[0] == 9){
//sending sms
} else {
return "error";
}
}

how to get length of integers in PHP ?

I want to get the length of integer values for validation in PHP.
Example:
Mobile numbers should be only 10 integer values. It should not be more than 10 or less than 10 and also it should not be included of alphabetic characters.
How can I validate this?
$num_length = strlen((string)$num);
if($num_length == 10) {
// Pass
} else {
// Fail
}
if (preg_match('/^\d{10}$/', $string)) {
// pass
} else {
// fail
}
This will work for almost all cases (except zero) and easily coded in other languages:
$length = ceil(log10(abs($number) + 1));
In my opinion, the best way is:
$length = ceil(log10($number))
A decimal logarithm rounded up is equal to length of a number.
If you are using a web form, make sure you limit the text input to only hold 10 characters as well to add some accessibility (users don't want to input it wrong, submit, get a dialog about their mistake, fix it, submit again, etc.)
Use intval function in loop,
See this example
<?php
$value = 16432;
$length=0;
while($value!=0) {
$value = intval($value/10);
$length++
}
echo "Length of Integer:- ".$length;
?>
$input = "03432 123-456"; // A mobile number (this would fail)
$number = preg_replace("/^\d/", "", $number);
$length = strlen((string) $number);
if ($number == $input && $length == 10) {
// Pass
} else {
// Fail
}
If you are evaluating mobile numbers (phone numbers) then I would recommend not using an int as your chosen data type. Use a string instead because I cannot forsee how or why you would want to do math with these numbers. As a best practice, use int, floats, etc, when you want/need to do math. Use strings when you don't.
From your question, "You want to get the lenght of an integer, the input will not accept alpha numeric data and the lenght of the integer cannot exceed 10. If this is what you mean; In my own opinion, this is the best way to achieve that:"
<?php
$int = 1234567890; //The integer variable
//Check if the variable $int is an integer:
if (!filter_var($int, FILTER_VALIDATE_INT)) {
echo "Only integer values are required!";
exit();
} else {
// Convert the integer to array
$int_array = array_map('intval', str_split($int));
//get the lenght of the array
$int_lenght = count($int_array);
}
//Check to make sure the lenght of the int does not exceed or less than10
if ($int_lenght != 10) {
echo "Only 10 digit numbers are allow!";
exit();
} else {
echo $int. " is an integer and its lenght is exactly " . $int_lenght;
//Then proceed with your code
}
//This will result to: 1234556789 is an integer and its lenght is exactly 10
?>
By using the assertion library of Webmozart Assert we can use their build-in methods to validate the input.
Use integerish() to validate that a value casts to an integer
Use length() to validate that a string has a certain number of characters
Example
Assert::integerish($input);
Assert::length((string) $input, 10); // expects string, so we type cast to string
As all assertions in the Assert class throw an Webmozart\Assert\InvalidArgumentException if they fail, we can catch it and communicate a clear message to the user.
Example
try {
Assert::integerish($input);
Assert::length((string) $input, 10);
} catch (InvalidArgumentException) {
throw new Exception('Please enter a valid phone number');
}
As an extra, it's even possible to check if the value is not a non-negative integer.
Example
try {
Assert::natural($input);
} catch (InvalidArgumentException) {
throw new Exception('Please enter a valid phone number');
}
I hope it helps 🙂
A bit optimazed answer in 2 or 3 steps depends if we allow negative value
if(is_int($number)
&& strlen((string)$number) == 10)
{
// 1 000 000 000 Executions take from 00:00:00.153200 to 00:00:00.173900
//Code
}
Note that will allow negative up to 9 numbers like -999999999
So if we need skip negatives we need 3rd comparision
if(is_int($number)
&& $number >= 0
&& strlen((string)$number) == 10)
{
// 1 000 000 000 Executions take from 00:00:00.153200
// to 00:00:00.173900 over 20 tests
}
Last case when we want from -1 000 000 000 to 1 000 000 000
if(is_int($number)
&& $number >= 0
&& strlen(str_replace('-', '', (string)$number)) == 10)
{
// 1 000 000 000 Executions take from 00:00:00.153200
// to 00:00:00.173900 over 20 tests
}
For compare
First naswer with regex
if (preg_match('/^\d{10}$/', $number)) {
// Fastest test with 00:00:00.246200
}
** Tested at PHP 8.0.12
** XAMPP 3.3.0
** Ryzen 7 2700
** MSI Radeon RX 5700 8G
Tested like
$function = function($number)
{
if(is_int($number)
&& $number >= 0
&& strlen((string)$number) == 10)
{
return true;
}
}
$number = 1000000000;
$startTime = DateTime::createFromFormat('U.u', microtime(true);
for($i = 0; $i < 1000000000; $i++)
{
call_user_func_array($function, $args);
}
$endTime = DateTime::createFromFormat('U.u', microtime(true);
echo $endTime->diff($startTime)->format('%H:%I:%S.%F');

Categories