1

This is the code in my controller:

$fields = array(
    "user_id[]" => "required"
);

print_r($this->request->getPost("user_id"));

$validate = $this->validate($fields);

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

I'm getting this output:

Array
(
    [0] => 7
    [1] => 17
)
{"user_id[]":"The user_id[] field is required."}

Why it's showing error when there has values?

Looking for help. Thanks in advance.

6
  • Can you try testing "user_id.0" => "required" and see if this validation works for you ? Commented Mar 12, 2021 at 18:58
  • @DhavalChheda, it's not marking as required then. I mean if nothing posted, it's not showing error. Commented Mar 12, 2021 at 19:34
  • Post the relevant HTML form Commented Mar 12, 2021 at 19:45
  • Can you var dump and show what you have passed with the modification of the code? Also you don't need $validation = \Config\Services::validation(); in your controller. You have to use $this->validator->getErrors() since Validator is already attached to the instance of Controller. Commented Mar 13, 2021 at 3:53
  • Also one issue is this particular line : $final_fields[$field] = $validate; . In CI4, Vaidator key is supposed to be string and arrays are represented with a dot parameter. So instead of $final_fields[$field] you have to do following: $final_fields.$field and this should be a string such as "user_id.0" then only the validator will be able to function properly. Refer : codeigniter4.github.io/userguide/libraries/… Commented Mar 13, 2021 at 3:59

1 Answer 1

1

Found a solution from CI forum.

Instead of this,

$fields = array(
    "user_id[]" => "required"
);

Write:

$fields = array(
    "user_id.*" => "required"
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.