PHP Codeigniter中的自定义验证 - 需要两个字段之一

Ale*_*duc 1 php forms validation codeigniter

我的表格有手机和手机领域.我希望用户填写其中一个字段,或两者都填写,但不能同时填写.

我已经看到了用其他语言做的方法,但是我可以就如何用Codeigniter做一些建议吗?

Sud*_*oti 7

你可以这样做:

$this->form_validation->set_rules('phone', 'Your validation message.', 'callback__phone_check');

并制作一个功能:

function _phone_check() {
   //check for phone and cellphone field.
  //make sure one field is not empty and return accordingly
}

希望有所帮助


The*_*tor 5

只是想以您的方式抛出一些快速的代码片段。我想完成这个,这个问题是我搜索时在 google 中的第一个条目。我从其他答案中获得灵感,这是我所做的对我有用的事情(YMMV):

$this->form_validation->set_message('contactVerify', 'Either Phone or Email is required');
...
$this->form_validation->set_rules('phone', 'Phone', 'trim|callback_contactVerify[email]|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|callback_contactVerify[phone]|valid_email|xss_clean');
...
public function contactVerify($contact, $otherField) {
  return ($contact != '' || $this->input->post($otherField) != '');
}
Run Code Online (Sandbox Code Playgroud)

由于这是一个非常简单的验证函数,我预先设置了错误消息,因此不必在验证函数中设置它。我通过方括号传入另一个我想检查的字段作为第二个参数。

希望这是有用的。