在密码symfony中添加特殊字符和数字

ffscu2ro  于 2023-06-24  发布在  其他
关注(0)|答案(2)|浏览(149)

对于我的项目,我必须创建用户,我想更改密码的属性。symfony automaticcaly为它定义6个字符,但我想添加特殊字符和数字在它。对于长度我很好,但对于其余的我找不到答案。
这是我的表格

->add('plainPassword', PasswordType::class, [
                // instead of being set onto the object directly,
                // this is read and encoded in the controller
                'mapped' => false,
                'attr' => ['autocomplete' => 'new-password'],
                'constraints' => [
                    new NotBlank([
                        'message' => 'Please enter a password',
                    ]),
                    new Length([
                        'min' => 6,
                        'minMessage' => 'Your password should be at least {{ limit }} characters',
                        // max length allowed by Symfony for security reasons
                        'max' => 4096,
                    ]),
                ],
            ])

你知道,如果我改变我的形式的属性就足够了吗?
谢谢你的帮助

gfttwv5a

gfttwv5a1#

查看Compound constraint
所以基本上你会创建自己的“规则集”。在本例中,用于密码。
为了至少有一个数字(数字)或/和一个特殊字符,你可以使用Regex Constrains。更准确地说,是其中的两个:

  • 匹配至少一个数字
  • 匹配至少一个特殊字符
// src/Validator/Constraints/MyPasswordRequirements.php

use Symfony\Component\Validator\Constraints\Compound;
use Symfony\Component\Validator\Constraints as Assert;

class MyPasswordRequirements extends Compound {

    protected function getConstraints(array $options): array
    {
        return [
            new Assert\NotBlank(),
            new Assert\Type('string'),
            new Assert\Length(['min' => 6]),
            //regex -> to have at elast one digit
            new Assert\Regex([
                'pattern' => '/\d+/i', 
            ]),
            //regex -> to have at elast one special char from the list
            //note: list of special-char is [#?!@$%^&*-]. Adjust to suite your needs
            new Assert\Regex([
                'pattern' => '/[#?!@$%^&*-]+/i', 
            ]),
        ];
    }
}

然后在你的表单中使用这个MyPasswordRequirements约束

->add('plainPassword', PasswordType::class, [
    'mapped' => false,
    'attr' => ['autocomplete' => 'new-password'],
    'constraints' => [
        new MyPasswordRequirements()
    ],
    // validation error message 
    'invalid_message' => 'Password requirements are not fulfilled'
])

**P.S.**我故意将reg-ex一分为二,只是为了更好地理解和演示。我可以将它们合并为一个,也许还可以添加更多的限制。看看Regex strong password the special characters

nszi6y05

nszi6y052#

在symfony 6.3中,可以使用PasswordStrength约束

use Symfony\Component\Validator\Constraints as Assert;
...
 #[Assert\PasswordStrength]

相关问题