Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate multidimensional arrays with Codeigniter and Jquery

Hi I need to validate a multidimensional form like this

<input type="text" class="input-xlarge span5 req" id="contact_first_name" name="hotel[<?=$id?>][contact_first_name]" value="<?= set_value('hotel[contact_first_name]') ?>">
<input type="text" class="input-xlarge span5 req" id="contact_last_name" name="hotel[<?=$id?>][contact_last_name]" value="<?= set_value('hotel[contact_last_name]') ?>">

I don't know the dimensions of the final array because the inputs are added dynamically via jquery.

I'm using Codeigniter Form_Validation for the server-side and via JQuery with the JQuery Validator for the client-side.

This is my form_validation rules

$config['add_hotel'] = array(
array(
    'field' => 'hotel[][hotel_name]', 
    'label' => 'Hotel Name', 
    'rules' => 'required'
    ),    
array(
    'field' => 'hotel[][contact_first_name]', 
    'label' => 'First Name', 
    'rules' => 'trim|required'
    ),
array(
    'field' => 'hotel[][contact_last_name]', 
    'label' => 'Last Name', 
    'rules' => 'trim|required'
    ),

and this is how i'm doing it via jquery validator

$("#add_hotel").validate({
rules: {
    "hotel[][hotel_name]": "required"

  /*  errorElement: "div",
    wrapper: "div"*/
},
messages: {
   "hotel[][hotel_name]": "Please enter the Association Name"
},
submitHandler: function(form) {
    form.submit();
}

Don't know how to validate each Hotel[] input with its own id, or maybe there is another way to defining the inputs that can be simpler.

like image 466
user1678153 Avatar asked Sep 17 '12 17:09

user1678153


1 Answers

Posted array

$hotel = $this->input->post('hotel');
if(!empty($hotel))
{
    // Loop through hotels and add the validation
    foreach($hotel as $id => $data)
    {
        $this->form_validation->set_rules('hotel[' . $id . '][contact_first_name]', 'First name', 'required|trim');
        $this->form_validation->set_rules('hotel[' . $id . '][contact_last_name]', 'Last name', 'required|trim');
    }
}

Default rules that apply all the time

$this->form_validation->set_rules('username', 'Username', 'required');

if ($this->form_validation->run() == FALSE)
{
    // Errors
}
else
{
    // Success
}
like image 66
Philo Avatar answered Oct 23 '22 11:10

Philo