codeigniter + require letters and numbers in password

chowwy picture chowwy · May 10, 2012 · Viewed 20.3k times · Source

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.

Answer

rjz picture rjz · May 10, 2012

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');