CodeIgniter Forums
model validationRules for nullable fields? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forum-28.html)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forum-30.html)
+--- Thread: model validationRules for nullable fields? (/thread-81022.html)



model validationRules for nullable fields? - lukmim - 01-14-2022

Is there a way of setting up model validation (for example "integer" or "numeric") for fields that are not required and also can be null?
I'm aware of the "if_exist" (doesn't allow null values) and "permit_empty" (permits also some non-null invalid values) rules, and also I figured "callback_" probably can't be used for this (unless I recreate all needed validation rules with callbacks that would allow null, for example callback_nullableInteger, callback_nullableNumeric, callback_nullableAlphaNumeric etc)


RE: model validationRules for nullable fields? - BilltheCat - 01-14-2022

You could always wrap your rules in normal PHP logic... I'm not sure what rules you could apply in this case, but this might be what you're looking for:

PHP Code:
$post $this->request->getPost();
$rules = [
        'username' => [
            'rules'  => 'required',
            'errors' => [
                'required' => 'You must choose a Username.',
            ],
        ],
        'email'    => [
            'rules'  => 'required|valid_email',
            'errors' => [
                'valid_email' => 'Please check the Email field. It does not appear to be valid.',
            ],
        ],
    ];


if(
is_int($post['fieldname']) || is_numeric($post['fieldname']) is_null($post['fieldname'])) {
$rules['fieldname'] = [
            'rules'  => 'is_unique'
        ];
}
$validation->setRules($rules); 



RE: model validationRules for nullable fields? - kenjis - 01-14-2022

It seems you are correct and there is no good way to do accept only null or integer.

(01-14-2022, 08:41 AM)lukmim Wrote: "permit_empty" (permits also some non-null invalid values) rules

What values are some non-null invalid values?


RE: model validationRules for nullable fields? - lukmim - 01-17-2022

(01-14-2022, 04:22 PM)kenjis Wrote: What values are some non-null invalid values?

empty array, empty string, and false