codeigniter/Pyro: making sure one of three fields is valid
I have three phone fields (work_phone, home_phone and cell_phone). I would like to make sure that the user fills out at least one of them. This is my validation so far.
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;
}
}
The problem is that it makes ALL the phone fields required. If I try if((!isset($_POST[work_phone])) ||(!isset($_POST[home_phone])) ){
no error is returned.
What's the best way to check if one of the three fields is not null?
EDIT
I got this to work by using empty()
instead of isset()
and &&
instead of ||
I know have
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;
}
}
Which works but returns the error three times
just change your !isset statements to isset:
if(isset($_POST['phone1') || isset($_POST['phone2']) || isset($_POST['phone3'])){
//at least 1 is filled.
}else{
//fail
}
how about using the CI input class... $this->input->post will return a false if its empty
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!";
}
Update for CI's validation...
If they haven't filled in any phone field, you could just add validation for the first one. Like so...
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!";
}
}
The answer is to use empty()
instead of isset()
see above.
精彩评论