Search code examples
phpcodeignitercodeigniter-4

How to make email field optional in Codeigniter 4 controller


I have this form validation in my Codeigniter 4 controller and I made the email field optional in the View, Now how can I also make the email field optional in the controller and validate the email ONLY IF THE USER Entered email address in the field. If the user omitted the email field, the email validation should be omitted.

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

Please help.


Solution

  • You can use if() condition if anyone enter email then use validation rules otherwise not need to use email validation rules like following code :

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