CodeIgniter强密码策略,带有强制大写/小写字母和数字

时间:2015-09-03 05:56:15

标签: php codeigniter validation passwords

我想要求用户选择一个至少包含一个大写字母和一个数字的强密码。在使用CodeIgniter验证表单时,如何强制执行此策略?

1 个答案:

答案 0 :(得分:1)

扩展默认的Form_validation类,并为自定义密码验证创建自定义验证规则。

要扩展默认课程,您需要创建一个MY_Form_validation课程并将其放入application/libraries/MY_Form_validation.php。这是一个例子:

<?php defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Extension of CI's default form validation library.
 *
 * @see system/libraries/Form_validation.php
 */
class MY_Form_validation extends CI_Form_validation {

    /**
     * Custom password validation rule.
     *
     * @param  string $pass Password to check.
     *
     * @return bool       
     */
    public function check_pass($pass)
    {
        // It's a good practice to make sure each validation rule does
        // its own job. So we decide that this callback does not check
        // for the password field being required. If we need so, we just
        // prepend the "required" rule. For example: "required|min_length[8]|check_pass"
        //
        // So we just let it go if the value is empty:
        if (empty($pass))
        {
            return TRUE;
        }

        // This sets the error message for your custom validation
        // rule. %s will be replaced with the field name if needed.
        $this->set_message('check_pass', 'Password needs to have at least one uppercase letter and a number.');

        // The regex looks ahead for at least one lowercase letter,
        // one uppercase letter and a number. IT'S NOT TESTED THOUGH.
        return (bool) preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/', $pass);
    }

}

使用此自定义类,设置规则时,控制器可以使用check_pass验证规则。

如果您懒得添加此自定义类,或者您已经在其他地方实现了验证功能,则可能需要通过将callback_添加到现有函数的名称并使用自定义验证回调来使用它们作为验证规则。有关详情,请参阅validation callbacks

我不推荐后一种方法,因为它弄乱了验证规则所在的位置。在某些情况下,我们必须使用不在验证类中的自定义回调,在这些情况之外(不属于您的情况)所有规则最好都在您的自定义类中。

P.S。还要考虑这个:

Password Strength