如何在 Codeigniter 4 控制器中使电子邮件字段可选

How to make email field optional in Codeigniter 4 controller

我在我的 Codeigniter 4 控制器中进行了此表单验证,我在视图中将电子邮件字段设置为可选,现在我怎样才能在控制器中将电子邮件字段设置为可选并仅在用户输入电子邮件地址时验证电子邮件在该领域。如果用户省略了电子邮件字段,则应省略电子邮件验证。

if ($this->request->getMethod() == 'post') {
        //let's do the validation here
        $rules = [
            'username' => 'required|min_length[3]|max_length[20]',
            'phone' => 'required|min_length[3]|max_length[20]',
            'email' => 'min_length[6]|max_length[50]|valid_email|is_unique[users.email]',
            'password' => 'required|min_length[8]|max_length[255]',
            'password_confirm' => 'matches[password]',
        ];

请帮忙。

如果有人输入电子邮件然后使用验证规则,您可以使用 if() 条件,否则不需要使用电子邮件验证规则,如以下代码:

 if($this->request->getVar('email')){
            $rules = [
                'username' => 'required|min_length[3]|max_length[20]',
                'phone' => 'required|min_length[3]|max_length[20]',
                'email' => 'min_length[6]|max_length[50]|valid_email|is_unique[users.email]',
                'password' => 'required|min_length[8]|max_length[255]',
                'password_confirm' => 'matches[password]',
            ];
        }else{
            $rules = [
                'username' => 'required|min_length[3]|max_length[20]',
                'phone' => 'required|min_length[3]|max_length[20]',
                'password' => 'required|min_length[8]|max_length[255]',
                'password_confirm' => 'matches[password]',
            ];
        }

要节省重复规则,您可以使用...

$rules = [
    'username' => 'required|min_length[3]|max_length[20]',
    'phone' => 'required|min_length[3]|max_length[20]',
    'password' => 'required|min_length[8]|max_length[255]',
    'password_confirm' => 'matches[password]',
];

if($this->request->getPost('email')){
    $rules['email'] = 'min_length[6]|max_length[50]|valid_email|is_unique[users.email]';
}