Welcome Guest, Not a member yet? Register   Sign In
Validate multiple input in CI 4
#1
Sad 

Hi,

This is the code in my controller:

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

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

$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();


I'm getting this output:

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

Looking for help. 
Thanks in advance.
Reply
#2

Well, actually not sure why you have tried such complicated coding but I would go simpler

PHP Code:
$user_id => $this->request->getVar('user_id');

foreach (
$user_id as $ui){
  if($ui == ''){
     $msg 'User id should not be empty';
     return redirect()->to(site_url('/admin/register'))->with('msg'$msg);
  }


Btw, can you write more specifically what was your need and desired result?
Reply
#3

@demyr,

You've used raw code for validation (not CI).

Simply, it's working well with,


PHP Code:
$fields = array(
    "user_id" => "required"
); 


But if there has multiple input with the single field like checkbox, the validation isn't working.

With this code:

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


It's shouldn't show this error,

Code:
{"user_id[]":"The user_id[] field is required."}


While there has values,


Code:
Array
(
    [0] => 7
    [1] => 17
)
Reply
#4

CodeIgniter 4 User Guide - Running Multiple Validations


permit_empty - Allows the field to receive an empty array, empty string, null or false.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#5

@InsiteFX,

Thanks. But if I add permit_empty and no value found, it won't show error.

I mean, if this code:

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

shows:

Code:
Array ()

Then the validation should show the error what I want.
But after adding permit_empty it won't show error.
Reply
#6

See https://codeigniter4.github.io/CodeIgnit...are-arrays
Reply
#7

@kenjis, Can you please implement it for my case? I don't understand how to make this from your link: https://codeigniter4.github.io/CodeIgnit...are-arrays
Reply
#8

I never tried it, but in your case:
PHP Code:
// The data to test:
'user_id' => [
    0 => 7,
    1 => 17,
]

$validation->setRules([
    'user_id.*' => 'required'
]); 
Reply
#9

@kenjis, it worked. Thank you so much.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB