I have had a similar scenario in Laravel and solved it in the following way.
The password contains characters from at least three of the following five categories:
- English uppercase characters (A – Z)
- English lowercase characters (a – z)
- Base 10 digits (0 – 9)
- Non-alphanumeric (For example: !, $, #, or %)
- Unicode characters
First, we need to create a regular expression and validate it.
Your regular expression would look like this:
^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[dx])(?=.*[!$#%]).*$
I have tested and validated it on this site. Yet, perform your own in your own manner and adjust accordingly. This is only an example of regex, you can manipluated the way you want.
So your final Laravel code should be like this:
'password' => 'required|
min:6|
regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[dx])(?=.*[!$#%]).*$/|
confirmed',
Update
As @NikK in the comment mentions, in Laravel 5.5 and newer the the password value should encapsulated in array Square brackets like
'password' => ['required',
'min:6',
'regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[dx])(?=.*[!$#%]).*$/',
'confirmed']
I have not testing it on Laravel 5.5 so I am trusting @NikK hence I have moved to working with c#/.net these days and have no much time for Laravel.
Note:
- I have tested and validated it on both the regular expression site and a Laravel 5 test environment and it works.
- I have used min:6, this is optional but it is always a good practice to have a security policy that reflects different aspects, one of which is minimum password length.
- I suggest you to use password confirmed to ensure user typing correct password.
- Within the 6 characters our regex should contain at least 3 of a-z or A-Z and number and special character.
- Always test your code in a test environment before moving to production.
- Update: What I have done in this answer is just example of regex password
Some online references
Regarding your custom validation message for the regex rule in Laravel, here are a few links to look at:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…