CodeIgniter Forums

Full Version: Form validation problem in Codeigniter 4
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.
Try adding "permit_empty" rule.

Example:

PHP Code:
$fields = array(
    "id" => "permit_empty|numeric"
); 
@nicojmb, it worked. Thanks.