How to added password validation rule in the validator?
Validation rule:
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
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:
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])(?=.*[\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 manipulate the way you want.
So your final Laravel regex rule should be like this:
'password' => [
'required',
'min:6',
'regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$/',
'confirmed'
]
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.
What I have done in this answer is just example of regex password
Regarding your custom validation message for the regex rule in Laravel, here are a few links to look at:
Laravel Validation custom message
Custom validation message for regex rule in Laravel?
Laravel custom validation messages
This doesn't quite match the OP requirements, though hopefully it helps. With Laravel you can define your rules in an easy-to-maintain format like so:
$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() );
}
Would output:
[
'The email must be a valid email address.',
'The password must be at least 10 characters.',
'The password format is invalid.',
]
(The regex rules share an error message by default—i.e. four failing regex rules result in one error message)
Since Laravel version 8, you can use built-in password validation:
// 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()
or you can chain them all
use Illuminate\Validation\Rules\Password;
$rules = [
'password' => [
'required',
'string',
Password::min(8)
->mixedCase()
->numbers()
->symbols()
->uncompromised(),
'confirmed'
],
]
A Custom Laravel Validation Rule will allow developers to provide a custom message with each use case for a better UX experience.
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.';
}
}
}
Then on your request validation:
$request->validate([
'email' => 'required|string|email:filter',
'password' => [
'required',
'confirmed',
'string',
new isValidPassword(),
],
]);
Sounds like a good job for regular expressions.
Laravel validation rules support regular expressions. Both 4.X and 5.X versions are supporting it :
4.2 : http://laravel.com/docs/4.2/validation#rule-regex
5.1 : http://laravel.com/docs/5.1/validation#rule-regex
This might help too:
http://www.regular-expressions.info/unicode.html
it's easy to do so with laravel 8:
$rules = array(
'name' => ['required'],
'email' => ['required','email','unique:ducks'],
'password' => ['required', 'confirmed',Password::min(8)
->letters()
->mixedCase()
->numbers()
->symbols()
->uncompromised()
],
);
See the doc , ( in your case you can ignore the uncompromised rule).
laravel 9 password validation
$request->validate([
'name' => 'required', 'string', 'max:255',
'email' => 'required', 'string', 'email', 'max:255', 'unique:users',
'password' => 'required|string|min:6|confirmed|regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-]).{6,}$/',
]);
Related
I have some problems with Laravel's validation. I'm using required_if validator.
What I want to achieve: When the hilightColorBool is true the hilightColor should be required, should be integer between min:1 and max:5.
...
'hilightColorBool' => 'required|boolean',
'hilightColor' => 'required_if:hilightColorBool,1|integer|min:1|max:5'
...
But when I'm doing it like above it always returns that hilghtColor is bool, when I do remove the integer, min and max from hilightColor it works good, but I need to validate anyway if it is integer between 1 and 5. It seems weird to me.
Going on from my comment, i may do it like this:
$rules = [
'hilightColorBool' => 'required|boolean',
];
if (is_bool($request->get('hilightColorBool'))) {
$rules['hilightColor'] = 'required|integer|min:1|max:5';
}
then simply do:
$request->validate($rules);
in my project. all mount maybe int or float or was even double.in database amount column type is varchar and for each choose amount by user i have simple limitation, for example amount must be more than some value and less that some value. but i get error validation in laravel.
$ps = DB::table('merchant_web_service')->whereCustomerKey($request->input('customer_key'))->first();
/* $ps->minimum_range_buy is 5 and $ps->maximum_range_buy is 10*/
$validate_amount = Validator::make($request->all(),
['amount' => "required|min:$ps->minimum_range_buy|max:$ps->maximum_range_buy"]);
validator error is:
"The amount must be at least 10 characters."
my test amount values: 1000,100.1
Since you didn't specify any rule for the input data type, it validates it as a string. Try numeric and between rules.
$validate_amount = Validator::make($request->all(),
['amount'=>
"required|numeric|between:$ps->minimum_range_buy,$ps->maximum_range_buy"
]);
try this
$rules = [
'your_field' => 'required|regex:/^\d*(\.\d{2})?$/'
]
For example, I have 2 tables : sites1 and sites2
I need to check that field url which is comes from my html form is unique.
Here my validation rule :
public function rules()
{
return [
'url' => unique:sites1|unique:sites2'
];
}
Unfortunately, this rule applies only for sites2 table. Is there any possible ways to validate both tables?
Your validation rule seems ok. Just make sure that both sites1 and sites2 table has field name url and both in same database.
Your unique:sites1 rule will be translated into SQL
select count(*) as aggregate from `sites1` where `url` = ?
While unique:sites2 rule will be translated into SQL
select count(*) as aggregate from `sites2` where `url` = ?
See if first SQL does return result. Long URL may result non unique if used with limited index length. It may be better if you could store hash value of URL so you can compare url just by using hash.
No need to maintain the same name in two different tables
In laravel 4.2
Validator::make(Input::all, [
'url' => 'unique:site1,your_column_name|unique:site2:your_column_name_2'
]);
Laravel 5.*:
$this->validate($request,[
'url' => 'unique:site1,your_column_name|unique:site2:your_column_name_2'
]);
Hopefully it's working fine.
In the above answer i think you can't use custom error message, you can do in another way just copy the filed in another field for the two checks.
public function validator(array $data)
{
$data = ['url2' => $data['email']];
$rules = [
'url' => 'unique:sites1',
'url2' => 'unique:sites2',
];
$messages = [
'url.unique' => 'url unique in site 1',
'url2.unique' => 'url unique in site 2',
];
return $validator = Validator::make($data, $rules, $messages);
}
if ($validator->fails()) {
if(!empty($validator->errors()->get('url2'))) {
$validator->errors()->add("url", 'url unique in site 2');
}
}
I have the following rules :
'Fno' => 'digits:10'
'Lno' => 'min:2|max5' // this seems invalid
But how to have the rule that
Fno should be a digit with minimum 2 digits to maximum 5 digits and
Lno should be a digit only with min 2 digits
If I correctly got what you want:
$rules = ['Fno' => 'digits_between:2,5', 'Lno' => 'numeric|min:2'];
or
$rules = ['Fno' => 'numeric|min:2|max:5', 'Lno' => 'numeric|min:2'];
For all the available rules: http://laravel.com/docs/4.2/validation#available-validation-rules
digits_between :min,max
The field under validation must have a length between the given min
and max.
numeric
The field under validation must have a numeric value.
max:value
The field under validation must be less than or equal to a maximum
value. Strings, numerics, and files are evaluated in the same fashion
as the size rule.
min:value
The field under validation must have a minimum value. Strings,
numerics, and files are evaluated in the same fashion as the size
rule.
$this->validate($request,[
'input_field_name'=>'digits_between:2,5',
]);
Try this it will be work
The complete code to write validation for min and max is below:
$request->validate([
'Fno' => 'integer|digits_between:2,5',
'Lno' => 'min:2',
]);
Laravel min and max validation do not work properly with a numeric rule validation. Instead of numeric, min and max, Laravel provided a rule digits_between.
$this->validate($request,[
'field_name'=>'digits_between:2,5',
]);
Also, there was just a typo in your original post.
'min:2|max5' should have been 'min:2|max:5'.
Notice the ":" for the "max" rule.
In addition to other answers, i have tried them but not worked properly. Below code works as you wish.
$validator = Validator::make($input, [
'oauthLevel' => ['required', 'integer', 'max:3', 'min:1']
]);
I want to validate username such a way that it should not accept the emoticons like :-),;-) etc.. but it should accept the special characters with the alphabets and numeric...tough one...
currently I have applied
$validator = Validator::make(Input::all(),array('username'=>'required|max:20|min:3');
thanks in advance
Something like this:
$validator = Validator::make(
Input::all(),
array('username'=> array('required',
'max:20',
'min:3',
'Regex:/\A(?!.*[:;]-\))[ -~]+\z/')
)
);
Note you can shorten the requirement like this:
$validator = Validator::make(
Input::all(),
array('username'=> array('required',
'Regex:/\A(?!.*[:;]-\))[ -~]{3,20}\z/')
)
);
Obviously, you need to complete with the other emiticons you want to forbid.
You can extend the allowed characters using . instead of [ -~] that limits the string to ascii characters.