Zinc
Zinc

Reputation: 385

How to validate only 1 array[] is required from 10 fields in CodeIgniter Form validation

I have a 1 Add User form that can add multiple user up to 10.

Now I need to validate only 1 field are required in form_validation rules. But, for sure what I need now is not a fixed field to validated. So, I can submit the data on the randomize field inside the form. (10 fields available, and only need 1 required field but once again not a fixed field because I was tried fixed field and really bothering me).

<form action="x" method="post" class="form-horizontal">
<?php for ($i=1; $i<=10; $i++) { ?>
   <div class="form-group">
      <label class="control-label col-sm-3">Username <?php echo $i; ?></label>
      <div class="col-sm-9">
         <input type="text" class="form-control" name="user[]">
      </div>
   </div>
<?php } ?>

Validation rules inside controller's function

if ( ! empty($this->input->post('user', TRUE)))
{
    $this->form_validation->set_rules('user[]', 'User', 'trim|alpha_numeric|min_length[2]');
}

I'm trying to add required into user[] validation rules, its not working because all user[] fields become required.

Then im trying to add $this->form_validation->set_rules('user[0]', 'User', 'trim|required|alpha_numeric|min_length[2]'); into the form validation rules, so the code is look like this.

if ( ! empty($this->input->post('user', TRUE)))
{
    $this->form_validation->set_rules('user[0]', 'User', 'trim|required|alpha_numeric|min_length[2]');
    $this->form_validation->set_rules('user[]', 'User', 'trim|alpha_numeric|min_length[2]');
}

It was successfully validated for one field are required that is Username 1 field on array 0. But sometimes it really bothering me to input only 1 new user only on Username 1.

Because sometimes I felt really easy to input on Username 4 or Username 9 because the cursor is near there.

Is there any way to validate this user[] fields for only required on 1 field no matter which fields is there. Like Username 3 maybe on Username 7.

Upvotes: 1

Views: 3361

Answers (2)

Cindy
Cindy

Reputation: 140

You can do a simple validation using foreach before creating a rules for your form_validation.

Just remove the required from your form_validation then what you need to do is validate the data is not empty, you can use 1 more helper variable to do it. for example, I'm using $data = 0.

$data = 0;
$user = $this->input->post('user', TRUE);
foreach ($user as $u) {
    if ($u != '')
    {
        $data++
    }
}

if ($data == 0) { /* then set some message to said "At least 1 data required" */ }
else 
{
   $this->form_validation->set_rules('user[]', 'User', 'trim|alpha_numeric|min_length[2]');
}

// then validate if form_validation run
if ($this->form_validation->run())
{
    // your code..
}

This will validate if $this->input->post('user', TRUE); input is all empty, then $data still be set on 0. If there is a user field submitted and not null, the $data will be set ++ to 1. So you can input the data wherever you wanted to maybe on user 1 or user 8 or any fields.

After the $data becomes 1 or more, you will set new validation of form_validation rules and then your code will run if the validation match with your requirements in the form_validation rules.

You can check the data are successfully submitted if the form_validation requirements are match using flashdata. If you want to check if requirements are not match, just using else.

if ($this->form_validation->run())
{
    $this->session->set_flashdata('message', 'We got your submitted user : '.$data.' username');
}

Upvotes: 2

Alex
Alex

Reputation: 9265

Short answer, no.

Looking at the main execute function in the form validation library you will see that determines if the $_POST field is an array, and if so, runs the validation function on each item of the array separately. You can confirm this by writing your own validation function and echoing something at the top of the function. It will run one iteration per item.

With that being said you could make a rule like this in libraries/MY_Form_validation.php:

public function required_array($unused, $config) {
    $config = explode(',', $config);
    $items = $_POST[$config[0]];
    $i = 0;
    foreach ($items as $item) {
        if (!empty($item)) {
            $i++;
        }
    }
    //echo 'num items: ' . $i;
    $req = isset($config[1]) ? $config[1] : 1;
    if ($i < $req) {
        $this->set_message('required_array', 'Atleast ' . $req . ' {field} must be filled in.');
        return false;
    } else {
        return true;
    }
}

use like: $this->form_validation->set_rules('user[]', 'User', 'required_array[user, 3]');

However not only is this a hack, this will never be reached if there are no items in the array as CI has a special way of dealing with requires that we can't/shouldn't modify to add our function as it is a system file and that is bad practice.

Here is the section of code from validation that prevents the solution from working:

    if (
        ($postdata === NULL OR $postdata === '')
        && $callback === FALSE
        && $callable === FALSE
        && ! in_array($rule, array('required', 'isset', 'matches'), TRUE)
    )
    {
        continue;
    }

So your best bet is to check to see if one is filled in outside of CI validation.

Upvotes: 0

Related Questions