如果您的用户要添加多个字段,您应该让他们使用HTML array input 来完成。比如:
<input name="my_array[]" />
这是form_validation 与 HTML 数组输入的用法:
- 获取输入数组以确定有多少字段
- 为每个字段设置规则
够简单吗? :) 这是我的演示代码:
控制器:application/controllers/test.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Test Controller
*
* It's really just a test controller
*
*/
class Test extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$data = array();
if ($this->input->post('test_submit'))
{
$this->load->library('form_validation');
$input_array = $this->input->post('test');
for ($i = 0; $i < count($input_array); $i++)
{
$this->form_validation->set_rules("test[$i]", 'Test Field '.($i + 1), 'trim|is_numeric|xss_clean');
}
if ($this->form_validation->run() === TRUE)
{
$data['message'] = 'All input are number! Great!';
}
}
$this->load->helper('form');
$this->load->view('test', $data);
}
}
/* End of file test.php */
/* Location: ./application/controllers/test.php */
查看:application/views/test.php
<p><?php echo isset($message) ? $message : ''; ?></p>
<?php echo validation_errors(); ?>
<?php echo form_open(); ?>
<?php echo form_label('Test fields (numeric)', 'test[]'); ?>
<?php for ($i = 0; $i < 3; $i++): ?>
<?php echo form_input('test[]', set_value("test[$i]")); ?>
<?php endfor; ?>
<?php echo form_submit('test_submit', 'Submit'); ?>
<?php echo form_close(); ?>
网址:<your_base_url_here>/index.php/test
看看吧:D
注意:numeric 和 is_numeric 规则都需要输入,这意味着空字符串不是数字。