如何使用Codeigniter和Jqueryvalidation多维数组
嗨,我需要validation这样的多维表单
<input type="text" class="input-xlarge span5 req" id="contact_first_name" name="hotel[][contact_first_name]" value=""> <input type="text" class="input-xlarge span5 req" id="contact_last_name" name="hotel[][contact_last_name]" value="">
我不知道最终数组的维度,因为输入是通过jquery动态添加的。
我正在使用Codeigniter Form_Validation用于服务器端,并通过JQuery使用JQuery Validator用于客户端。
这是我的form_validation规则
$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' ),
这就是我通过jqueryvalidation器做的方式
$("#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(); }
不知道如何使用自己的idvalidation每个Hotel[]
输入,或者可能有另一种方法来定义可以更简单的输入。
发布数组
$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'); } }
始终适用的默认规则
$this->form_validation->set_rules('username', 'Username', 'required'); if ($this->form_validation->run() == FALSE) { // Errors } else { // Success }
Codeigniter有一种非常严格的方式来处理命名为数组的输入的validation规则,它只会validation字段名称是否完全相同,所以规则
array( 'field' => 'hotel[][hotel_name]', 'label' => 'Hotel Name', 'rules' => 'required' ),
只有当该字段实际上被命名为hotel [] [hotel_name]时才会起作用。
由于这不是字段的名称(实际名称类似于hotel [1] [hotel_name]),因此Codeigniter不会对其进行validation。
您可以使用dinamically生成配置数组,但我认为您最好分别为这些字段编写自己的validation规则。