我正试图使用codeigniter的set_rules
函数对变量值进行验证。有可能做到吗?
我的代码如下:
$client_name = "Some name";
$this->form_validation->set_rules($client_name,'Client','required');
甚至我也尝试过直接在Post变量中设置值,如下所示:
$a = array('Name1','','Name3');
foreach($a as $client_name ) {
$_POST['client_name'] = $client_name = "Some name";
echo "--- " . validation_errors();
$this->form_validation->set_rules('client_name','Client','required');
if (!$this->form_validation->run())
{
echo validation_errors();
}
else
{
echo 'validation successful';
}
}
该代码给出以下输出:
--- // No validation error
validation successful //first time validation successfully ran
--- // No validation error
Client field is required //first time validation failed
--Client field is required // validation error from the second loop
Client field is required
如果可能的话,请帮忙。
提前谢谢。
我找到了以下解决方案:
$a = array('Name1','','Name3');
foreach($a as $client_name ) {
$this->load->library('form_validation',null,'fv');
$_POST['client_name'] = $client_name = "Some name";
echo "--- " . validation_errors();
$this->fv->set_rules('client_name','Client','required');
if (!$this->fv->run())
{
echo validation_errors();
}
else
{
echo 'validation successful';
}
unset($this->fv);
}
到目前为止,它是有效的,但如果有人找到更好的解决方案,请回答这个问题。因为我觉得循环加载库不是一个好的做法。