Zend Framework 2表格带密码

时间:2013-07-09 09:06:10

标签: zend-framework2 zend-form zend-db-table

我正在使用zend框架2,我如何强制用户设置了8个字符的密码,但字母和数字都是? 这是我的代码:

$this->add(array(
        'name' => 'password',
        'attributes' => array(
            'type'        => 'password',
            'id'          => 'password',
            'class'       => 'span12 noradius',
            'placeholder' => 'Password'
        ),
        'options' => array(
            'label' => 'Password :'
        )
    ));

1 个答案:

答案 0 :(得分:4)

您可以编写自定义验证程序,请查看:http://framework.zend.com/manual/2.0/en/modules/zend.validator.writing-validators.html

class MyValid\PasswordStrength extends Zend\Validator\AbstractValidator
{
    const LENGTH = 'length';
    const UPPER  = 'upper';
    const LOWER  = 'lower';
    const DIGIT  = 'digit';

    protected $messageTemplates = array(
        self::LENGTH => "'%value%' must be at least 8 characters in length",
        self::UPPER  => "'%value%' must contain at least one uppercase letter",
        self::LOWER  => "'%value%' must contain at least one lowercase letter",
        self::DIGIT  => "'%value%' must contain at least one digit character"
    );

    public function isValid($value)
    {
        $this->setValue($value);

        $isValid = true;

        if (strlen($value) < 8) {
            $this->error(self::LENGTH);
            $isValid = false;
        }

        if (!preg_match('/[A-Z]/', $value)) {
            $this->error(self::UPPER);
            $isValid = false;
        }

        if (!preg_match('/[a-z]/', $value)) {
            $this->error(self::LOWER);
            $isValid = false;
        }

        if (!preg_match('/\d/', $value)) {
            $this->error(self::DIGIT);
            $isValid = false;
        }

        return $isValid;
    }
}

然后选择自定义验证器:

$inputFilter->add($factory->createInput(array(
    'name'     => 'password',
    'required' => true,
    'validators' => array(
        array(
            // What ever your namespace is etc determines this..
            'name'    => 'My\Validator\PasswordStrength',
        ),
    ),
)));