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


Custom Validation in PHP Codeigniter - one of two fields required

我的表单有一个手机和一个电话字段。我希望用户填写其中一个字段,或者两个都填写,而不是两个都填写。

我已经在其他语言中看到了这样做的方法,但是我可以有一些关于如何使用Codeigniter的建议吗?

您可以这样做:

<>之前$this->form_validation->set_rules('phone', '您的验证消息')"、"callback__phone_check");之前

创建一个函数:

<>之前函数_phone_check() {//检查电话和手机字段。//确保一个字段不为空并返回}之前

希望有帮助

只是想以您的方式抛出一些快速代码片段。我想做到这一点,这个问题是我在谷歌搜索的第一个条目之一。我从其他答案中获得了灵感,以下是我所做的对我有用的(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) != '');
}

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

只需在客户端进行JS验证,在服务器端进行PHP验证(或使用CI的表单助手)…总之,PHP应该是这样的:

if ($_POST['cellphone'] == '' OR $_POST['phone' == '') {
// do stuff like make an notification, alert, etc... and take users back to the form
}