Laravel密码验证规则

时间:2015-07-21 12:59:50

标签: php laravel validation laravel-5

如何在验证器中添加密码验证规则?

验证规则:

密码包含以下五个类别中至少三个的字符:

  • 英文大写字母(A - Z)
  • 英文小写字母(a - z)
  • 基数为10位(0 - 9)
  • 非字母数字(例如:!,$,#或%)
  • Unicode字符

如何在验证器规则中添加上述规则?

我的代码

// create the validation rules ------------------------
    $rules = array(
        'name'             => 'required',                        // just a normal required validation
        'email'            => 'required|email|unique:ducks',     // required and must be unique in the ducks table
        'password'         => 'required',
        'password_confirm' => 'required|same:password'           // required and has to match the password field
    );

    // do the validation ----------------------------------
    // validate against the inputs from our form
    $validator = Validator::make(Input::all(), $rules);

    // check if the validator failed -----------------------
    if ($validator->fails()) {

        // get the error messages from the validator
        $messages = $validator->messages();

        // redirect our user back to the form with the errors from the validator
        return Redirect::to('home')
            ->withErrors($validator);

    }

7 个答案:

答案 0 :(得分:83)

我在Laravel中遇到了类似的情况,并通过以下方式解决了这个问题。

密码包含以下五个类别中至少三个的字符:

  • 英文大写字母(A - Z)
  • 英文小写字母(a - z)
  • 基数为10位(0 - 9)
  • 非字母数字(例如:!,$,#或%)
  • Unicode字符

首先,我们需要创建一个正则表达式并对其进行验证。

您的正则表达式如下所示:

^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$

我已经在this网站上对其进行了测试和验证。然而,以自己的方式执行自己的工作并相应地进行调整。这只是正则表达式的一个例子,你可以按照你想要的方式进行操作。

所以你最后的Laravel代码应该是这样的:

'password' => 'required|
               min:6|
               regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\X])(?=.*[!$#%]).*$/|
               confirmed',

<强>更新 正如@NikK在评论中提到的那样,在Laravel 5.6中,密码值应该封装在数组方括号中,如

'password' => ['required', 
               'min:6', 
               'regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\X])(?=.*[!$#%]).*$/', 
               'confirmed']

我没有在Laravel 5.6上进行测试,所以我相信@NikK因此我现在已经开始使用c#/ .net,并且没有太多时间用于Laravel。

注意:

  1. 我已经在正则表达式网站和Laravel 5测试环境中测试并验证了它,并且它可以正常工作。
  2. 我使用过min:6,这是可选的,但最好有一个反映不同方面的安全策略,其中一个是最小密码长度。
  3. 我建议您使用密码确认以确保用户输入正确的密码。
  4. 在6个字符中,我们的正则表达式应包含至少3个a-z或A-Z以及数字和特殊字符。
  5. 在转向生产之前,始终在测试环境中测试您的代码。
  6. 更新:我在这个答案中所做的只是正则表达式密码的例子
  7. 一些在线参考

    关于Laravel中正则表达式规则的自定义验证消息,以下是一些要查看的链接:

答案 1 :(得分:4)

虽然希望有所帮助,但这与OP的要求不太匹配。借助Laravel,您可以使用以下易于维护的格式定义规则:

    $inputs = [
        'email'    => 'foo',
        'password' => 'bar',
    ];

    $rules = [
        'email'    => 'required|email',
        'password' => [
            'required',
            'string',
            'min:10',             // must be at least 10 characters in length
            'regex:/[a-z]/',      // must contain at least one lowercase letter
            'regex:/[A-Z]/',      // must contain at least one uppercase letter
            'regex:/[0-9]/',      // must contain at least one digit
            'regex:/[@$!%*#?&]/', // must contain a special character
        ],
    ];

    $validation = \Validator::make( $inputs, $rules );

    if ( $validation->fails() ) {
        print_r( $validation->errors()->all() );
    }

将输出:

    [
        'The email must be a valid email address.',
        'The password must be at least 10 characters.',
        'The password format is invalid.',
    ]

(正则表达式规则默认情况下会共享一条错误消息-即,四个失败的正则表达式规则会导致一条错误消息)

答案 2 :(得分:3)

对于正则表达式来说听起来不错。

Laravel验证规则支持正则表达式。 4.X和5.X版本都支持它:

这也可能有所帮助:

http://www.regular-expressions.info/unicode.html

答案 3 :(得分:3)

现在你可以使用 Laravel 密码验证了

    // Require at least 8 characters...
Password::min(8)

// Require at least one letter...
Password::min(8)->letters()

// Require at least one uppercase and one lowercase letter...
Password::min(8)->mixedCase()

// Require at least one number...
Password::min(8)->numbers()

// Require at least one symbol...
Password::min(8)->symbols()

或者你可以将它们全部链接起来

use Illuminate\Validation\Rules\Password;

'password' => [
            'required',
            'string',
            Password::min( 8 )->mixedCase()->numbers()->symbols()->uncompromised(),
            'confirmed'
        ],

来源@https://laravel.com/docs/8.x/validation#validating-passwords

答案 4 :(得分:1)

自定义Laravel验证规则将使开发人员可以为每个用例提供自定义消息,以获得更好的UX体验。

function copyStyling() { // This is a standalone script let masterID = "1107dQEIAbZ8ipBi0wvU6cdy4OV7N2hURT5fjgOwm_vY"; let childID = "1XvGARRBzXofsjrFJkl8SCmt3tQJ2nkw1n9MG3tr9fhU"; // Master Slide Variables let masterPresentation = SlidesApp.openById(masterID); let masterSlide = masterPresentation.getSlides()[0]; let masterElements = masterSlide.getPageElements(); // Get style elements let masterBackground = masterSlide.getBackground(); let masterSolidFill = masterBackground.getSolidFill().getColor(); // etc // ... // Child Slide Variables let childPresentation = SlidesApp.openById(childID); let childSlide = childPresentation.getSlides()[0]; let childElements = childSlide.getPageElements(); // Updating the stylings for the page let childBackground = childSlide.getBackground(); childBackground.setSolidFill(masterSolidFill); // etc // ... // Updating the stylings for each element on the page masterElements.forEach((element, i) => { childElements[i].setLeft(element.getLeft()); childElements[i].setTop(element.getTop()); // etc // ... }); }

php artisan make:rule IsValidPassword

然后根据您的要求进行验证:

namespace App\Rules;

use Illuminate\Support\Str;
use Illuminate\Contracts\Validation\Rule;

class isValidPassword implements Rule
{
    /**
     * Determine if the Length Validation Rule passes.
     *
     * @var boolean
     */
    public $lengthPasses = true;

    /**
     * Determine if the Uppercase Validation Rule passes.
     *
     * @var boolean
     */
    public $uppercasePasses = true;

    /**
     * Determine if the Numeric Validation Rule passes.
     *
     * @var boolean
     */
    public $numericPasses = true;

    /**
     * Determine if the Special Character Validation Rule passes.
     *
     * @var boolean
     */
    public $specialCharacterPasses = true;

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $this->lengthPasses = (Str::length($value) >= 10);
        $this->uppercasePasses = (Str::lower($value) !== $value);
        $this->numericPasses = ((bool) preg_match('/[0-9]/', $value));
        $this->specialCharacterPasses = ((bool) preg_match('/[^A-Za-z0-9]/', $value));

        return ($this->lengthPasses && $this->uppercasePasses && $this->numericPasses && $this->specialCharacterPasses);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        switch (true) {
            case ! $this->uppercasePasses
                && $this->numericPasses
                && $this->specialCharacterPasses:
                return 'The :attribute must be at least 10 characters and contain at least one uppercase character.';

            case ! $this->numericPasses
                && $this->uppercasePasses
                && $this->specialCharacterPasses:
                return 'The :attribute must be at least 10 characters and contain at least one number.';

            case ! $this->specialCharacterPasses
                && $this->uppercasePasses
                && $this->numericPasses:
                return 'The :attribute must be at least 10 characters and contain at least one special character.';

            case ! $this->uppercasePasses
                && ! $this->numericPasses
                && $this->specialCharacterPasses:
                return 'The :attribute must be at least 10 characters and contain at least one uppercase character and one number.';

            case ! $this->uppercasePasses
                && ! $this->specialCharacterPasses
                && $this->numericPasses:
                return 'The :attribute must be at least 10 characters and contain at least one uppercase character and one special character.';

            case ! $this->uppercasePasses
                && ! $this->numericPasses
                && ! $this->specialCharacterPasses:
                return 'The :attribute must be at least 10 characters and contain at least one uppercase character, one number, and one special character.';

            default:
                return 'The :attribute must be at least 10 characters.';
        }
    }
}

答案 5 :(得分:0)

使用 laravel 8 很容易做到:

 $rules = array(
    'name'             => ['required'],                        
    'email'            => ['required','email','unique:ducks'],     
    'password'         => ['required', 'confirmed',Password::min(8)
                                                   ->letters()
                                                   ->mixedCase()
                                                   ->numbers()
                                                   ->symbols()
                                                   ->uncompromised()
                           ],
);

请参阅 doc ,(在您的情况下,您可以忽略不妥协的规则)。

答案 6 :(得分:0)

来自 Laravel 8 文档 https://laravel.com/docs/8.x/validation#validating-passwords

[
 'password' => Password::min(8)
->letters()
->mixedCase()
->numbers()
->symbols()
]