Welcome Guest, Not a member yet? Register   Sign In
model validationRules for nullable fields?
#1

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)
Reply
#2

(This post was last modified: 01-14-2022, 02:20 PM by BilltheCat.)

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); 
Reply
#3

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?
Reply
#4

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

empty array, empty string, and false
Reply




Theme © iAndrew 2016 - Forum software by © MyBB