codeigniter / Pyro:确保三个字段中的一个有效

时间:2011-03-05 02:10:53

标签: php validation codeigniter

我有三个电话字段(work_phone,home_phone和cell_phone)。我想确保用户至少填写其中一个。到目前为止,这是我的验证。

array(
    'field' => 'work_phone',
    'label' => 'lang:employee.work_phone',
    'rules' => 'max_length[10]|numeric|callback_check_phones[work_phone]'
    ),
array(
    'field' => 'home_phone',
    'label' => 'lang:employee.home_phone',
    'rules' => 'max_length[10]|numeric|callback_check_phones[home_phone]'
    ),
array(
    'field' => 'cell_phone',
    'label' => 'lang:employee.cell_phone',
    'rules' => 'max_length[10]|numeric|callback_check_phones[cell_phone]'
    ),

function check_phones($value,$name) {
    if((!isset($_POST[$name]))) {
        $this->form_validation->set_message('check_phones', 
            'You must enter at least one phone number');
        return FALSE;
    }
    else
    {
        return TRUE;
    }
}

问题在于它需要所有手机字段。如果我尝试if((!isset($_POST[work_phone])) ||(!isset($_POST[home_phone])) ){,则不会返回任何错误。 检查三个字段中的一个是否为空的最佳方法是什么?

修改 我使用empty()代替isset()&&代替||我知道有

function check_phones($value){
    if((empty($_POST['work_phone'])) && (empty($_POST['home_phone'])) && (empty($_POST['cell_phone']))){
        $this->form_validation->set_message('check_phones', 'You must enter at least one phone number');
        return FALSE;
    }
    else
    {
        return TRUE;
    }

}

哪个有效,但三次返回错误

3 个答案:

答案 0 :(得分:1)

只需将您的!isset语句更改为isset:

if(isset($_POST['phone1') || isset($_POST['phone2']) || isset($_POST['phone3'])){
   //at least 1 is filled.
}else{
   //fail
}

答案 1 :(得分:1)

如何使用CI输入类... $ this-> input-> post如果为空则返回false


if($this->input->post('work_phone') || $this->input->post('home_phone') || $this->input->post('cell_phone'))
    {
        echo "We have your phone!";
    }
    else
    {
        echo "Please enter at least one!";
    }

更新CI验证..

如果他们没有填写任何电话字段,您只需添加第一个验证。像这样......


if($_SERVER['REQUEST_METHOD'] == "POST")
{
    if($this->input->post('work_phone') || $this->input->post('home_phone') || $this->input->post('cell_phone'))
    {
        echo "At least one is in there";
    }
    else
    {
        $this->form_validation->set_rules('work_phone', '1 Phone', 'required');
//      echo "Please enter at least one!";
    }
}

答案 2 :(得分:0)

答案是使用empty()代替isset()见上文。