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
- atleast one small char
- atleast one big char
- atleast one number
- atleast one special char
- 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 ?
Custom Validation Rule Using Closures $validator = Validator::make($request->post(),[ 'birth_year'=>[ 'required', function($attribute, $value, $fail){ if($value >= 1990 && $value <= date('Y')){ $fail("The :attribute must be between 1990 to ". date('Y').". "); } } ] ]);
To get the exact words to validate you can make use of Rule::in method available with laravel. Using Rule::in method whatever the values provided by this rule has to be matched otherwise it will fail.
We added the validation code in the store() method that validates the 'name' field, but we have not displayed any error message. To display the error message, laravel has provided the error variable that displays the error message. It can be used as: {{$errors->first('name')}}
Validation is the most important aspect while designing an application. It validates the incoming data. By default, base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP requests with a variety of powerful validation rules.
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])(?=.*[!$#%]).*$/
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.
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