Codeigniter array backend validation

2020-04-28 20:41发布

问题:

I'm using a form, inside which contains a div with a pair of input field which is added dynamically.

VIEW:

<?php echo form_open_multipart('location/add'); ?>
<div>
<input type="text" name="title[]"/>
<div id="infoMessage"><?php echo form_error('title[]'); ?></div>
</div>
<div>
<input type="text" name="desc[]"/>
<div id="infoMessage"><?php echo form_error('desc[]'); ?></div>
</div>
<div>
<input type="text" name="link[]"/>
<div id="infoMessage"><?php echo form_error('link[]'); ?></div>
</div>  

<input type="submit" name="" value="enter">  
<?php echo form_close(); ?> 

Now, Initially I don't want validation for this 3 input fields but I want the backend validation for all the input fields that are going to add dynamically(by clicking on +) on pressing submit button.

CONTROLLER:

    public function add()
    {

        $this->form_validation->set_rules('title[]','Title','required');
        $this->form_validation->set_rules('desc[]','Description','required');
        $this->form_validation->set_rules('link[]','Link','required');

            if ($this->form_validation->run() == FALSE)
            {
                $this->load->view('test');
            }
            else
            {
                ....
            }

    }

回答1:

You can use custom callback validation function EX:

public function add()
{
    $this->form_validation->set_rules('title', 'Title', 'callback_title_validate');
    if ($this->form_validation->run() == FALSE)
    {
        $this->load->view('test');
    }
    else
    {
        //....
    }
}

function title_validate($title){
    foreach($title as $key=>$value){
        if($title[$key]==null || $title[$key]==false){
        $this->form_validation->set_message('title_validate', 'The Title field is Required.');
            return FALSE;
        }
        }
    return TRUE;
}