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';
This is my code to check if the field is empty and it works fine, however i want to check for both, if its empty and if its got less than 10 characters
<pre>
if(empty($_POST['comments'])){ $errors[]="Please enter a comment."; }
</pre>
I tried this
<pre>
if(empty($_POST['comments'])){ $errors[]="Please enter a comment."; }
if(strlen($_POST['comments']) > 10){ $errors[]="Please enter a comment."; }
</pre>
However this then made neither work so i tried which had the same result with neither of them working
<pre>
if(empty($_POST['comments']) && strlen($_POST['comments']) > 10)){ $errors[]="Your
comment must be longer than 10 characters."; }
</pre>
I have tried mb_strlen as well but that changed nothing.
Your logic is a bit off. You're currently adding the error if the string is empty and longer than 10 characters (which would be a paradox.)
You need to check if the string is empty or less then 10 characters.
Try this:
if (empty($_POST['comments']) || strlen($_POST['comments']) < 10) {
$errors[] = "Your comment must be longer than 10 characters.";
}
That condition checks if the string is either empty or if the string has less < than 10 characters.
&& means and
|| means or
< means less than
> means greater than
You can read more about logical and comparison operators in the manual.
I what to validate a field so it will throw an error if its value empty or the length is less than or equal to 10.
But it only validates when its empty if the length is 1 or more it submits the value.
Need Help here to make it validate
if (empty($_POST["comment"]) && $_POST["comment"] <= 10) {
$comment_err = "Please send a message more than 10 characters";
}
else {
$comment = sanitize($_POST["comment"]);
}
Your question is not clear and precise, but I think what you're looking for if :
Throw an error if variable is empty
Throw an error if variable length is less than 10
So use OR ( || ) in your if statement, and strlen() to get variable length (as outlined in comment by Funk Forty Niner):
if(empty($_POST["comment"]) || strlen($_POST["comment"]) <= 10){
$comment_err = "Please send a message more than 10 characters";
}
else{
$comment = sanitize($_POST["comment"]);
}
Just check the length. If it's greater than 10 length, then it's definitely not empty, so you don't need to check for that explicitly.
if(isset($_POST["comment"]) && strlen($_POST["comment"]) > 10){
isset is just there to prevent an undefined index warning if that comment key doesn't exist.
(This reverses your if and else blocks, by the way, because it checks for good data instead of the error condition.)
This was partially answered in the comments, but Funk Forty Niner is such a generous soul that he gives away his wisdom for free with no expectation of fake internet points, all he asks for in return is some r e s p e c t when he comes home.
You have two problems in your code:
first your condition is not correct, you cannot have at the same time an empty index and checking his size. So you should have empty($_POST["comment"]) || $_POST["comment"] <= 10
you also cannot check the length of a string by checking the value against an integer, as #Funk Forty Niner told in comments, you have to use strlen() function http://php.net/manual/en/function.strlen.php
so your final code will be:
if(empty($_POST["comment"]) || strlen($_POST["comment"]) <= 10){
$comment_err = "Please send a message more than 10 characters";
}
else{
$comment = sanitize($_POST["comment"]);
}
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.
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');