CodeIgniter Forums
Form validation problem in Codeigniter 4 - 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: Form validation problem in Codeigniter 4 (/thread-78324.html)



Form validation problem in Codeigniter 4 - ciddict - 01-03-2021

Hi,

This is the code in my crontroller:

PHP Code:
$fields = array(
    "id" => "numeric"
);

$final_fields = array();

//to remove the fields if the post request doesn't found
foreach ($fields as $field => $validate) {
    if (!is_null($this->request->getPost($field))) {
        $final_fields[$field] = $validate;
    }
}

if (!
$final_fields) {
    return true;
}

$validate $this->validate($final_fields);

if (!
$validate) {
    $validation = \Config\Services::validation();
    $message $validation->getErrors();
    echo json_encode($message);
    exit();



This code is working fine.

But the problem is, if I submit empty value, it's also giving error.

Code:
{"id":"The id field must contain only numbers."}


This field is not required, so why it's showing error?
Where am I wrong? Please help. Thanks in advance.


RE: Form validation problem in Codeigniter 4 - nicojmb - 01-03-2021

Try adding "permit_empty" rule.

Example:

PHP Code:
$fields = array(
    "id" => "permit_empty|numeric"
); 



RE: Form validation problem in Codeigniter 4 - ciddict - 01-03-2021

@nicojmb, it worked. Thanks.