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

dojqjjoe  于 2022-12-07  发布在  其他
关注(0)|答案(3)|浏览(129)

我在我的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]',
        ];

请帮帮忙。

xzabzqsa

xzabzqsa1#

要保存复制规则的时间,您可以使用...

$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]';
}
hpxqektj

hpxqektj2#

你可以使用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]',
            ];
        }
gorkyyrv

gorkyyrv3#

使用验证规则'permit_empty'

'email' => [
               'label'  => 'Email',
               'rules'  => 'permit_empty|valid_email|is_unique[user.email]',
               'errors' => [
                  'required' => VALIDATION_MANDATORY_MSG,
                  'is_unique' => 'It is already exist'
               ]
           ],

相关问题