使用codeigniter验证表单

时间:2012-05-22 20:40:48

标签: validation codeigniter-2

我有以下表格:

<label>One</label> 
 Product ID:<input type="text" name="productid[]" value=""> 
 Product Quantity: <input type="text" name="quantity[]" value=""> <br>

<label>Two</label> 
 Product ID:<input type="text" name="productid[]" value=""> 
 Product Quantity: <input type="text" name="quantity[]" value=""> <br>

<label>Three</label> 
 Product ID:<input type="text" name="productid[]" value=""> 
 Product Quantity: <input type="text" name="quantity[]" value=""> <br>

 <!-- there may be more inputs like above (users can create new inputs 
    as many as they want) // I have a jquery function to create new rows-->


  <input type="submit" value="submit">

现在我的问题是如何在我的表单中输入类似于name="productid[]"而不是name="productid"的名称时使用Codeigniter验证表单。

通常我用来验证我的表单way,但这次它不适用于上面的表单。

如何验证?

2 个答案:

答案 0 :(得分:0)

你试过this ......?指南下面几行......

答案 1 :(得分:0)

您可以使用带有括号的文字字段名称:

$this->form_validation->set_rules('product_id[]', 'Product', 'required');
$this->form_validation->set_rules('quantity[]', 'Quantity', 'required');

这将使用该名称在每个字段上运行验证。如果必须再次验证特定索引,请再次使用文字字段名称(并在HTML中指定索引):

// <input name="product_id[3]">
$this->form_validation->set_rules('product_id[3]', 'Product', 'required');

全部在documentation for Codeigniter's Form Validation class

  

使用数组作为字段名称

     

Form Validation类支持将数组用作字段   名。考虑这个例子:

     

<input type="text" name="options[]" value="" size="50" />

     

如果您确实使用数组作为字段名称,则必须使用EXACT   Helper Functions中的数组名称   需要字段名称,并作为验证规则字段名称。

     

例如,要为上述字段设置规则,您可以使用:

     

$this->form_validation->set_rules('options[]', 'Options', 'required');

     

或者,要显示上述字段的错误,您可以使用:

     

<?php echo form_error('options[]'); ?>

     

或者重新填充您将使用的字段:

     

<input type="text" name="options[]" value="<?php echo set_value('options[]'); ?>" size="50" />

     

您也可以使用多维数组作为字段名称。对于   例如:

     

<input type="text" name="options[size]" value="" size="50" />

     

甚至:

     

<input type="text" name="sports[nba][basketball]" value="" size="50" />

     

与我们的第一个示例一样,您必须使用中的确切数组名称   辅助函数:

     

<?php echo form_error('sports[nba][basketball]'); ?>

     

如果您使用具有多个复选框(或其他字段)   选项,不要忘记在每个选项后留下一个空括号,所以   所有选择都将添加到POST数组中:

     

<input type="checkbox" name="options[]" value="red" />
<input type="checkbox" name="options[]" value="blue" />
<input type="checkbox" name="options[]" value="green" />

     

或者如果您使用多维数组:

     

<input type="checkbox" name="options[color][]" value="red" />
<input type="checkbox" name="options[color][]" value="blue" />
<input type="checkbox" name="options[color][]" value="green" />

     

当您使用辅助功能时,您将括号括起来   好:

     

<?php echo form_error('options[color][]'); ?>