强制使用 uppercase/lowercase 个字母和数字的 CodeIgniter 强密码策略

CodeIgniter strong password policy with compulsory uppercase/lowercase letters and digits

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

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

要扩展默认 class,您需要创建一个 MY_Form_validation class 并将其放入您的 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);
    }

}

有了这个自定义 class,check_pass 验证规则将在设置规则时对您的控制器可用。

如果您懒得添加此自定义 class 或者您已经在其他地方实现了验证功能,您可能希望通过在 callback_ 的名称前添加自定义验证回调现有功能并将它们用作验证规则。有关更多信息,请参阅 validation callbacks

我不推荐后一种方法,因为它会混淆验证规则所在的位置。在某些情况下,我们必须使用不在验证 class 中的自定义回调,在这些情况之外(不是你的)所有规则最好在你的自定义 class 中。

P.S。还要考虑这个: