If your users are going to add a number of fields, you should let them do it with HTML array input. Something like:
<input name="my_array[]" />
Here is form_validation usage with HTML array input:
- Get the input array to determine how many fields are there
- Set rules for each field
Simple enough? :) Here is my demo code:
Controller: 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 */
View: 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(); ?>
URL: <your_base_url_here>/index.php/test
Check it out :D
NOTE: numeric and is_numeric rules both require input, which mean empty strings are not numeric.