How to added password validation rule in the validator?
Validation rule:
The password contains characters from at least three of the following five categories:
How to add above rule in the validator rule?
My Code Here
// 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); }
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:
First, we need to create a regular expression and validate it.
Your regular expression would look like this:
^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$
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])(?=.*[\d\x])(?=.*[!$#%]).*$/| 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])(?=.*[\d\x])(?=.*[!$#%]).*$/', '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:
Some online references
Regarding your custom validation message for the regex rule in Laravel, here are a few links to look at:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With