16

Below is my rule for password:

return [
    'Password'                  => 'required|min:8|max:100|regex:[a-z{1}[A-Z]{1}[0-9]{1}]',
    'Password_confirmation'     => 'required|min:8|max:100|regex:[a-z{1}[A-Z]{1}[0-9]{1}]',
];

I am trying to add the rule such that it must have

  1. atleast one small char
  2. atleast one big char
  3. atleast one number
  4. atleast one special char
  5. min 8 chars

I tried this and it works required|confirmed|min:8|max:100|regex:/^[\w]{1,}[\W]{1,}$/, on a regex tester software . but not sure why it does not work in Laravel

Am I missing something ?

0

2 Answers 2

26

Use:

return [
    'password' => [
        'required',
        'confirmed',
        'min:8',
        'max:50',
        'regex:/^(?=.*[a-z|A-Z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$/',
    ]
];

Firstly, you do not need to check the confirmation separately. Just use the confirmed rule.

The expression you were using was invalid, and had nothing to do with what you wanted. I do suggest you do some research on regular expressions.

Due to the fact that the expression shown above uses pipes (|), you can specify the rules using an array.

Edit: You could also use this expression, which appears to have been tested a little more thoroughly.

/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\X])(?=.*[!$#%]).*$/
Sign up to request clarification or add additional context in comments.

1 Comment

Setting a low limit on the number of characters a user can use for their password can lead to a bad user experience, especially when the user is using a password manager which generates passwords beyond 20 characters or they want to use a phrase as their password.
7

You might want to check the PasswordStrengthPackage. It registers new validation rules that do what you need and are much more readable than a regular expression. So in your case you can have this:

return [
    'Password' => 'required|min:8|max:100|case_diff|numbers|letters|symbols|confirmed'
];

The Password_confirmation rule is not needed as long as the confirmation value is present and you add the confirmed rule for the Password field.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.