CodeIgniter Forums
"valid_date" validation does not prevent submission of spaces - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: "valid_date" validation does not prevent submission of spaces (/showthread.php?tid=81418)



"valid_date" validation does not prevent submission of spaces - umizoomi - 02-26-2022

I am using the Validation library to check that a date is either empty or a valid date using the following rules:


PHP Code:
$validation->setRules(array(
    'date' => array(
        'label' => 'Date',
        'rules' => 'permit_empty|valid_date[m/d/Y]'
    ),
)); 

However, when a user submits input that contain only spaces, it passes the validation. I know that I can trim the result and check if it is empty, but it seems like this should error out.


RE: "valid_date" validation does not prevent submission of spaces - kenjis - 02-27-2022

Because you set `permit_empty`.


RE: "valid_date" validation does not prevent submission of spaces - umizoomi - 02-27-2022

(02-27-2022, 06:19 PM)kenjis Wrote: Because you set `permit_empty`.

Personally, I don't think that should be expected behavior, even with `permit_empty` being set. The PHP function empty will return FALSE if a variable is passed in with just whitespace. For example

PHP Code:
$a " ";
echo empty(
$a) ? "EMPTY" "NOT EMPTY"

That would print out "NOT EMPTY". Why would permit_empty be any different? Therefore, if `permit_empty|valid_date[m/d/Y]` is set for validatin, I would expect that only input submitted with a value of FALSE, NULL, "", or a properly formatted date would be accepted.


RE: "valid_date" validation does not prevent submission of spaces - paulbalandan - 02-27-2022

Hi! When using the `permit_empty` rule, CI4 checks if the value provided is either an array or a string. If an array, it checks whether it is an empty array. If a string or can be casted to string, it trims it first then check against an empty string.
https://github.com/codeigniter4/CodeIgniter4/blob/7dc2ece32401ebde67122f7d2460efcaee7c352e/system/Validation/Validation.php#L234

Since you said you're passing an encapsed whitespace, CI4 trims it first. Naturally, this will pass the permit_empty check.