除了 Elijan Sejic 的正确回答之外,我还编写了以下函数来帮助设置验证规则并获取错误和值:
在 MY_Form_validation.php 中:
function set_rules_array($name, $label, $rules)
{
for ($i = 0; $i < count($_POST[$name]); $i++)
{
$this->set_rules("{$name}[$i]", $label, $rules);
}
}
在我打电话的助手中form2
:
function form2_error($name)
{
static $array_fields = array();
// if the last 2 characters are [], then handle this as an array field.
if (substr($name, -2) === '[]')
{
// If this field has been form2_error'd before, then increment the index, otherwise set to zero.
$array_fields[$name] = ! isset($array_fields[$name]) ? 0 : $array_fields[$name] + 1;
$name = substr($name, 0, -2) . '[' . $array_fields[$name]. ']';
}
return form_error($name);
}
function form2_set_value($name)
{
static $array_fields = array();
// if the last 2 characters are [], then handle this as an array field.
if (substr($name, -2) === '[]')
{
// If this field has been form2_error'd before, then increment the index, otherwise set to zero.
$array_fields[$name] = ! isset($array_fields[$name]) ? 0 : $array_fields[$name] + 1;
$name = substr($name, 0, -2) . '[' . $array_fields[$name]. ']';
}
return set_value($name);
}
如果您的表单有一个“添加更多”按钮并且您不知道预期有多少数组元素,这将特别有用。