Codeigniter表单验证 - 至少需要一个字段

时间:2015-05-20 19:01:38

标签: php codeigniter

我有一个包含3个字段的提交表单。在提交之前,至少应填写一个字段。你能帮我用codeigniter表单验证吗?

控制器

$this->form_validation->set_rules('country', 'Country','trim|strip_tags');
$this->form_validation->set_rules('state','State','trim|strip_tags');
$this->form_validation->set_rules('city','City','trimstrip_tags');

4 个答案:

答案 0 :(得分:1)

不是大师,但这将是我的方法......

function do_add()
{
   if( (isset($_POST['country']) || (isset($_POST['state']) || (isset($_POST['city']) )
   {
      //Do stuff
   }
   else
   {
      //Redirect or whatever
   }
}

答案 1 :(得分:1)

$this->form_validation->set_rules('country','Country','trim|strip_tags|callback_validate_either');
$this->form_validation->set_rules('state','State','trim|strip_tags|callback_validate_either');
$this->form_validation->set_rules('city','City','trimstrip_tags|callback_validate_either');

添加回调验证功能

function validate_either(){
    if($this->input->post('country') || $this->input->post('state') || $this->input->post('city')){
        return TRUE;
    }else{
        $this->form_validation->set_message('validate_either', 'Please enter atleast one of City , State or Country');
        return FALSE;
    }
}

通过Codeigniter文档,通过传递方法名称(不带“ callback_”前缀)来设置错误消息:

答案 2 :(得分:0)

如果复制代码,则第三条规则中缺少一个管道。另外,您可以将required规则设置为每个规则的第一条规则。

$this->form_validation->set_rules('country', 'Country','required|trim|strip_tags');
$this->form_validation->set_rules('state','State','required|trim|strip_tags');
$this->form_validation->set_rules('city','City','required|trim|strip_tags');

CI Rule Reference

答案 3 :(得分:0)

您可能需要使用自定义验证

$this->form_validation->set_rules('country', 'Country','trim|strip_tags|callback_validate_either');
$this->form_validation->set_rules('state','State','trim|strip_tags|callback_validate_either');
$this->form_validation->set_rules('city','City','trimstrip_tags|callback_validate_either');

然后添加验证功能

function validate_either(){
       if($this->input->post('country') || $this->input->post('state') || $this->input->post('city')){
            return TRUE;
       }else{
            $this->form_validation->set_message('validate_name', 'Please enter atleast one of City , State or Country');
        return FALSE;
       }
    }