PHP: Validation for required field - php

I want to validate a field which is required. I am using following condition to check whether the field is not empty:
isset($value) && !empty($value)
But if I write 0 in the fields, it will still say the field is required. The empty() function considers 0 as an empty value as told in PHP manual but what else should I do? I have tried writing many conditions but they didn't work as expected.
I saw user contributions and found:
empty($var) && !is_bool($var)
I tried adding it to my condition like this but didn't work:
isset($value) && !empty($value) && is_bool($value)

Try below code:
$value = 0;
if(isset($value) && $value !== "")
{
echo "Field not required";
}
else
{
echo "Field required";
}
Output:
Field not required
Demo:
http://3v4l.org/JWJbj
Explanation:
The integer 0 is truthy. It means that anything that checks it in a boolean'ish manner will treat it as false. In particular, !empty($value) will evaluate to false, so is_numeric would never even get a chance to fail.
Short version: empty is too wishy-washy in this case. Check for null and '' explicitly (with data-type hence used !==).

You can't check for empty. Basically you can only stick to the isset test.
If a field in the form was not filled this variable field will not be inside the $_POST superglobal and isset will return false. If the user typed 0 the variable name will exist inside $_POST isset will return true.

I would do it as following:
function emptyTextValue($value)
{
return trim((string) $value) !== '';
}

You know that all you get is a string, so you don't need full functionality of empty() function:
isset($_POST['yourFieldName']) && $_POST['yourFieldName'] !== ''

You can replace the empty function by :
$value !== ""
If it's not exactly empty, then it will validate the condition.

What I've done for my test is convert the empty check to a strlen check. Because PHP is so friendly, you can run a string comparison on the value. A value of null will return a 0 length string, while a value of 0 will return a length of 1. So what I've done is this:
if(isset($val) && strlen($val) > 0){
// Do stuff
}

Try
isset($value) && $value != ''

I have found a nice condition by myself.
$value === 0 || $value === "0" ? isset($value) : isset($value) && !empty($value)
This works perfectly for every case.

I would check to be sure that the form had been submitted and then trim the field 'msg' in case there were any white space chars, i.e. newlines, carriage returns, tabs, spaces and then test that result to make sure it's not the empty string as follows:
<?php
if ( isset($_POST['msg']) && trim($_POST['msg']) !== '') {
// other code
}

Related

how to check if variable is empty in php [duplicate]

if ($user_id == NULL || $user_name == NULL || $user_logged == NULL) {
$user_id = '-1';
$user_name = NULL;
$user_logged = NULL;
}
if ($user_admin == NULL) {
$user_admin = NULL;
}
Is there any shortest way to do it ?
And if i right, it should be tested with is_null?
It's possible $user_id, $user_name and $user_logged write in one line (maybe array?) without repeating NULL ?
If you want to test whether a variable is really NULL, use the identity operator:
$user_id === NULL // FALSE == NULL is true, FALSE === NULL is false
is_null($user_id)
If you want to check whether a variable is not set:
!isset($user_id)
Or if the variable is not empty, an empty string, zero, ..:
empty($user_id)
If you want to test whether a variable is not an empty string, ! will also be sufficient:
!$user_id
You can check if it's not set (or empty) in a number of ways.
if (!$var){ }
Or:
if ($var === null){ } // This checks if the variable, by type, IS null.
Or:
if (empty($var)){ }
You can check if it's declared with:
if (!isset($var)){ }
Take note that PHP interprets 0 (integer) and "" (empty string) and false as "empty" - and dispite being different types, these specific values are by PHP considered the same. It doesn't matter if $var is never set/declared or if it's declared as $var = 0 or $var = "". So often you compare by using the === operator which compares with respect to data type. If $var is 0 (integer), $var == "" or $var == false will validate, but $var === "" or $var === false will not.
here i have explained how the empty function and isset works please use the one that is appropriate also you can use is_null function also
<?php
$val = 0;
//evaluates to true because $var is empty
if (empty($val)) {
echo '$val is either 0, empty, or not set at all';
}
//evaluates to true because $VAR IS SET
if (isset($val)) {
echo '$val is set even though it is empty';
}
?>
empty() is a little shorter, as an alternative to checking !$user_id as suggested elsewhere:
if (empty($user_id) || empty($user_name) || empty($user_logged)) {
}
To check for null values you can use is_null() as is demonstrated below.
if (is_null($value)) {
$value = "MY TEXT"; //define to suit
}
Please define what you mean by "empty".
The test I normally use is isset().
you can use isset() routine .
also additionaly you can refer an range of is_type () functions like
is_string(), is_float(),is_int() etc to further specificaly test
1.
if(!($user_id || $user_name || $user_logged)){
//do your stuff
}
2 . No. I actually did not understand why you write such a construct.
3 . Put all values into array, for example $ar["user_id"], etc.
<?php
$nothing = NULL;
$something = '';
$array = array(1,2,3);
// Create a function that checks if a variable is set or empty, and display "$variable_name is SET|EMPTY"
function check($var) {
if (isset($var)) {
echo 'Variable is SET'. PHP_EOL;
} elseif (empty($var)) {
echo 'Variable is empty' . PHP_EOL;
}
}
check($nothing);
check($something);
check($array);
Its worth noting - and I only found this out after nearly 9 years of PHP coding that the best way of checking any variable exists is using the empty() function. This is because it doesn't generate errors and even though you turn them off - PHP still generates them! empty() however won't return errors if the variable doesn't exist. So I believe the correct answer is not to check if its null but to do the following
if (!empty($var) && is_null($var))
Note the PHP manual
variable is considered empty if it does not exist or if its value equals FALSE
As opposed to being null which is handy here!
Felt compelled to answer this because of the other responses. Use empty() if you can because it covers more bases. Future you will thank me.
For example you will have to do things like isset() && strlen() where instead you could use empty(). Think of it like this empty is like !isset($var) || $var==false
The best and easiest way to check if a variable is empty in PHP is just to use the empty() function.
if empty($variable)
then
....

How to detect when "0" is supplied as a form/$_POST value?

I'm trying to determine whether or not there is a value passed, but the value CAN be 0 ...
isset always returns true, and empty returns false because the value is 0
How can I get around this?
try
bool array_key_exists ( mixed $key , array $array )
like
if (array_key_exists("var1", $_POST)) {
// positive case, var1 was posted
if ($_POST["var1"] == 0){
// var1 was posted and 0
}else{
// var1 was posted and is not 0
}
}
more details are given at the docs.
The values of the $_POST array is all strings. Use the === operator:
if ($_POST['key'] === '0') {
// do things
}
Try this
if (isset($_POST['name']) && $_POST['name'] != 0)) {
/your Code/
}
What about simply checking whether the value is empty:
if (isset($_POST['key']) && $_POST['key'] !== '')) {
//'key' is set and not empty
}
All post values are strings, so consider:
isset($a[i]) && strlen($a[i])
Which will be true if and only if a value (except "an empty string") is supplied. Unlike with empty, which would return FALSE, this will also detect when "0" was passed as a value. Unlike the proposed solution, it will not be true when "" was supplied: thus it truly detects when a value was passed.
Also, array_key_exists and isset for $_POST keys will work the same, as there will no NULL values; arguably the critical check is that for a non-empty string. Once a value has been determined to exist (per the above/desired rules), it can be processed as appropriate - e.g. if ($a[i] > 0) or if ($a[i] == 0).

php validation prevents entering 0 as a value?

I have a field in a form for entering the number of masters titles won by a Tennis player. Some players have 0 titles. Even though my validation checks for an empty field I cannot enter 0. What changes do I need to make to allow 0 to be entered?
if (empty($_POST["masters"])) {
$has_errors = true;
$mastersErr = "Enter 0-10";
} else {
$masters = validate_input($_POST["masters"]);
}
use if ($_POST["masters"] === '') { to check for empty string
this is because
empty($variable) returns true if $variable equals false, null, '' (empty string) or 0
you can't use $_POST['masters'] == '' because in PHP statement 0 == '' is true
you have to use === operator
please also mind $_POST['xxx'] === 0 will never work because values in $_POST are strings
Anyway if you want user to put number between 0-10 I would suggest to do this check
if(is_numeric($var) && ($var >= 0) && ($var <= 10) && (intval($var) == $var))
{
// OK
}else
{
// not OK
}
This is because space character will pass $_POST["masters"] === '' check.
In validation you should always create if statements keeping in mind to check "is this value OK", not "is this value bad". For example if you want to validate email you dont' check "is value empty" "is value a number" "is value a float", you check "is value a email"|
is_numeric() is good, because
is_numeric('') is false
is_numeric(' ') is false
is_numeric(0) is true
but beware! because
is_numeric('0.1') is also true...
...so you need another check:
(intval($var) == $var) - this is how you make sure user entered integer (not float) number
PHP Manual:
http://www.php.net/manual/en/language.operators.comparison.php
http://www.php.net/is_numeric
http://www.php.net/intval

empty and zero as a string

How do I write an if condition that will evaluate a zero as not empty? I'm writing a validation script and if the field is blank, I throw an error. In the case of a select with numerical values that start with 0 (zero), that should not considered to be empty. The manual states that a string 0 is considered to be empty and returns false. If I change empty to !isset, the zero works but the other textboxes that are truly empty pass validation. How do I write this to handle my case?
if (strlen($x)) {
// win \o/ (not empty)
}
Happy coding.
(All text box / form input content is inherently just text. Any meaning as a numerical value comes later and each representation can be validated. 0 is coerced back to "0" in strlen.)
Have you considered using is_null()?
if (is_null($value) || $value === "") {}
if (empty($value) && $value !== 0)
if(!is_numeric($var) && empty($var))
{
// empty
}
else
{
// not empty
}

In where shall I use isset() and !empty()

I read somewhere that the isset() function treats an empty string as TRUE, therefore isset() is not an effective way to validate text inputs and text boxes from a HTML form.
So you can use empty() to check that a user typed something.
Is it true that the isset() function treats an empty string as TRUE?
Then in which situations should I use isset()? Should I always use !empty() to check if there is something?
For example instead of
if(isset($_GET['gender']))...
Using this
if(!empty($_GET['gender']))...
isset vs. !empty
FTA:
"isset() checks if a variable has a
value including (False, 0 or empty
string), but not NULL. Returns TRUE
if var exists; FALSE otherwise.
On the other hand the empty() function
checks if the variable has an empty
value empty string, 0, NULL or
False. Returns FALSE if var has a
non-empty and non-zero value."
In the most general way :
isset tests if a variable (or an element of an array, or a property of an object) exists (and is not null)
empty tests if a variable (...) contains some non-empty data.
To answer question 1 :
$str = '';
var_dump(isset($str));
gives
boolean true
Because the variable $str exists.
And question 2 :
You should use isset to determine whether a variable exists ; for instance, if you are getting some data as an array, you might need to check if a key isset in that array.
Think about $_GET / $_POST, for instance.
Now, to work on its value, when you know there is such a value : that is the job of empty.
Neither is a good way to check for valid input.
isset() is not sufficient because – as has been noted already – it considers an empty string to be a valid value.
! empty() is not sufficient either because it rejects '0', which could be a valid value.
Using isset() combined with an equality check against an empty string is the bare minimum that you need to verify that an incoming parameter has a value without creating false negatives:
if( isset($_GET['gender']) and ($_GET['gender'] != '') )
{
...
}
But by "bare minimum", I mean exactly that. All the above code does is determine whether there is some value for $_GET['gender']. It does not determine whether the value for $_GET['gender'] is valid (e.g., one of ("Male", "Female","FileNotFound")).
For that, see Josh Davis's answer.
isset is intended to be used only for variables and not just values, so isset("foobar") will raise an error. As of PHP 5.5, empty supports both variables and expressions.
So your first question should rather be if isset returns true for a variable that holds an empty string. And the answer is:
$var = "";
var_dump(isset($var));
The type comparison tables in PHP’s manual is quite handy for such questions.
isset basically checks if a variable has any value other than null since non-existing variables have always the value null. empty is kind of the counter part to isset but does also treat the integer value 0 and the string value "0" as empty. (Again, take a look at the type comparison tables.)
If you have a $_POST['param'] and assume it's string type then
isset($_POST['param']) && $_POST['param'] != '' && $_POST['param'] != '0'
is identical to
!empty($_POST['param'])
isset() is not an effective way to validate text inputs and text boxes from a HTML form
You can rewrite that as "isset() is not a way to validate input." To validate input, use PHP's filter extension. filter_has_var() will tell you whether the variable exists while filter_input() will actually filter and/or sanitize the input.
Note that you don't have to use filter_has_var() prior to filter_input() and if you ask for a variable that is not set, filter_input() will simply return null.
When and how to use:
isset()
True for 0, 1, empty string, a string containing a value, true, false
False for null
e.g
$status = 0
if (isset($status)) // True
$status = null
if (isset($status)) // False
Empty
False for 1, a string containing a value, true
True for null, empty string, 0, false
e.g
$status = 0
if(empty($status)) // true
$status = 1
if(empty($status)) // False
isset() vs empty() vs is_null()
isset is used to determine if an instance of something exists that is, if a variable has been instantiated... it is not concerned with the value of the parameter...
Pascal MARTIN... +1
...
empty() does not generate a warning if the variable does not exist... therefore, isset() is preferred when testing for the existence of a variable when you intend to modify it...
isset() is used to check if the variable is set with the value or not and Empty() is used to check if a given variable is empty or not.
isset() returns true when the variable is not null whereas Empty() returns true if the variable is an empty string.
isset($variable) === (#$variable !== null)
empty($variable) === (#$variable == false)
I came here looking for a quick way to check if a variable has any content in it. None of the answers here provided a full solution, so here it is:
It's enough to check if the input is '' or null, because:
Request URL .../test.php?var= results in $_GET['var'] = ''
Request URL .../test.php results in $_GET['var'] = null
isset() returns false only when the variable exists and is not set to null, so if you use it you'll get true for empty strings ('').
empty() considers both null and '' empty, but it also considers '0' empty, which is a problem in some use cases.
If you want to treat '0' as empty, then use empty(). Otherwise use the following check:
$var .'' !== '' evaluates to false only for the following inputs:
''
null
false
I use the following check to also filter out strings with only spaces and line breaks:
function hasContent($var){
return trim($var .'') !== '';
}
Using empty is enough:
if(!empty($variable)){
// Do stuff
}
Additionally, if you want an integer value it might also be worth checking that intval($variable) !== FALSE.
I use the following to avoid notices, this checks if the var it's declarated on GET or POST and with the # prefix you can safely check if is not empty and avoid the notice if the var is not set:
if( isset($_GET['var']) && #$_GET['var']!='' ){
//Is not empty, do something
}
$var = '';
// Evaluates to true because $var is empty
if ( empty($var) ) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if ( isset($var) ) {
echo '$var is set even though it is empty';
}
Source: Php.net
isset() tests if a variable is set and not null:
http://us.php.net/manual/en/function.isset.php
empty() can return true when the variable is set to certain values:
http://us.php.net/manual/en/function.empty.php
<?php
$the_var = 0;
if (isset($the_var)) {
echo "set";
} else {
echo "not set";
}
echo "\n";
if (empty($the_var)) {
echo "empty";
} else {
echo "not empty";
}
?>
!empty will do the trick. if you need only to check data exists or not then use isset other empty can handle other validations
<?php
$array = [ "name_new" => "print me"];
if (!empty($array['name'])){
echo $array['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array2 = [ "name" => NULL];
if (!empty($array2['name'])){
echo $array2['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array3 = [ "name" => ""];
if (!empty($array3['name'])){
echo $array3['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array4 = [1,2];
if (!empty($array4['name'])){
echo $array4['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array5 = [];
if (!empty($array5['name'])){
echo $array5['name'];
}
//output : {nothing}
?>
Please consider behavior may change on different PHP versions
From documentation
isset() Returns TRUE if var exists and has any value other than NULL. FALSE otherwise
https://www.php.net/manual/en/function.isset.php
empty() does not exist or if its value equals FALSE
https://www.php.net/manual/en/function.empty.php
(empty($x) == (!isset($x) || !$x)) // returns true;
(!empty($x) == (isset($x) && $x)) // returns true;
When in doubt, use this one to check your Value and to clear your head on the difference between isset and empty.
if(empty($yourVal)) {
echo "YES empty - $yourVal"; // no result
}
if(!empty($yourVal)) {
echo "<P>NOT !empty- $yourVal"; // result
}
if(isset($yourVal)) {
echo "<P>YES isset - $yourVal"; // found yourVal, but result can still be none - yourVal is set without value
}
if(!isset($yourVal)) {
echo "<P>NO !isset - $yourVal"; // $yourVal is not set, therefore no result
}

Categories