[英]Codeigniter - How to validate dynamic INPUT array?
I am not being able to run validation on an array of input fields. 我无法在输入字段数组上运行验证。 When I submit the form, it is submitted OK (data is saved correctly), but without validation (no errors, no messages). 当我提交表单时,它被提交确定(正确保存了数据),但是没有验证(没有错误,没有消息)。
Any idea what I'm doing wrong? 知道我在做什么错吗?
My view: 我的观点:
<?php echo form_open('save', array('id' => 'form')); ?>
<?php foreach ($cars as $row): ?>
<table>
<tr>
<td>
<h2>
<?php echo $row->cars_name; ?>
</h2>
</td>
<th>
Number
</th>
<td>
<?php echo form_input("car[$row->cars_id][cars_number]", $row->cars_number); ?>
</td>
</tr>
<tr>
<td>
</td>
<th>
Registry
</th>
<td>
<?php echo form_input("car[$row->cars_id][cars_number_reg]", $row->cars_number_reg); ?>
</td>
</tr>
</table>
<?php endforeach; ?>
<?php echo form_close(); ?>
My config/form_validation.php : 我的config / form_validation.php :
'test/save' => array(
array(
'field' => 'car[]', // also tried car[][], but no go
'label' => 'Field',
'rules' => 'alpha|htmlspecialchars|trim'
),
),
My controller: 我的控制器:
function save()
{
if ($this->form_validation->run() == FALSE) {
$json['success'] = '0';
$json['message'] = validation_errors();
echo json_encode($json);
} else {
$car = $this->input->post('car');
foreach ($car as $k => $v) {
$data['cars_number'] = $v['cars_number'];
$data['cars_number_reg'] = $v['cars_number_reg'];
$cars_id = $k;
$this->emergency_model->save($data, $cars_id);
}
$json['success'] = '1';
echo json_encode($json);
}
}
From the user guide form_validation 从用户指南form_validation
You must use the "exact" name for validation rules. 您必须使用“精确”名称作为验证规则。 In your case validation rules should be generated in foreach, same as your view. 在您的情况下,验证规则应在foreach中生成,与您的视图相同。
$validation_rules = array();
foreach($cars as $row){
$validation_rules[] = array( 'field'=>'car['.$row->cars_id.'][cars_number]',
'Field',
'rules' => 'alpha|htmlspecialchars|trim'
);
}
$this->form_validation->set_rules($validation_rules);
(note:this code was not tested) (注意:此代码未经测试)
I think you have to do this in controller instead of config. 我认为您必须在控制器而不是配置中执行此操作。
我建议像本教程中一样使用回调验证功能
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.