Search code examples
validationcodeigniterpasswordscodeigniter-2

codeigniter + require letters and numbers in password


I'd like to use form validation to require a password that has BOTH alpha and numeric characters. Here's what I've come up with so far:

$this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]|min_length[8]|alpha_numeric');

The issue is that "alpha_numeric" requires that the password only contain letters or numbers, it doesn't require both. Going for the stronger password option here.


Solution

  • You could set up a callback in your controller:

    public function password_check($str)
    {
       if (preg_match('#[0-9]#', $str) && preg_match('#[a-zA-Z]#', $str)) {
         return TRUE;
       }
       return FALSE;
    }
    

    Then, update your rule to use it:

    $this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]|min_length[8]|alpha_numeric|callback_password_check');