Laravel rule validation for numbers - php

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']
]);

Related

Laravel: Validate min and max value based on input fields

I am trying to add validation for the min and max values. Both these values are coming from input fields.
I want to validate that max value (max_price) should always be greater than min value (min_price).
I am working on the Laravel 5.7
$validator = validator($request->all(),[
'min_price' => 'required|min:1"',
'max_price' => 'required|numeric|min:min_price',
]);
You can use the code below
$validator=validator($request->all(),[
'min_price'=>'required|min:1',
'max_price' => 'required|gt:min_price'
]);
References
https://laravel.com/docs/5.7/validation#rule-gt
https://laravel.com/docs/5.7/validation#rule-min
You can use the rule gt (Greather than) that expect the number of another field as first argument:
'min_price'=>'required|numeric|min:30',
'max_price'=>'required|numeric|gt:min_price'

Laravel required_if does not accept other parameters

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);

Laravel validate int or float numbers as string

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})?$/'
]

Laravel password validation rule

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,}$/',
]);

Laravel form input integer length

In Laravel form input validation, you can specify a minimum and a maximum length of a given input field.
$inputRules = [
'postCode' => 'min:3|max:8'
];
Validation outcome
'BA45TZ' = true
'FF' = false
'GH22 55XYZ' = false
However if I do the same for a number, it will validate whether the input is less than or greater than the input, then return on that.
$inputRules = [
'cv2' => 'min:3|max:4'
];
Validation outcome
'586' = false
'4' = true
'2' = false
'3' = true
I actually want to validate a numbers length not it's numerical value. I can't figure out how to do this. Google has been no help, or I am not searching the right thing.
Anybody had any experience with this?
EDIT: I have answered my own question. I had missed Laravels digits_between.
Like an idiot, I missed Laravels digits_between validator rule. I swear I had scoured those rules, but here we are.
Thank you everyone for your help.
$inputRules = [
'cv2' => 'required|numeric|digits_between:3,4'
];
That's the expected behavior of Laravel's size, min and max validations. You can't change it.
For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value. For files, size corresponds to the file size in kilobytes.
To solve this you have to create a custom validation rule.
Something like this:
Validator::extend('min_length', function($attribute, $value, $parameters){
return strlen($value) >= $parameters[0];
});
Validator::extend('max_length', function($attribute, $value, $parameters){
return strlen($value) <= $parameters[0];
});
And you can use them in the same way:
'cv2' => 'min_length:3|max_length:4'
For length in number you've to use size, but you can't put ranges in it. So, the best thing to do is making a custom validation.
Here is the documentation in laravel: http://laravel.com/docs/5.0/validation#custom-validation-rules
And an example:
Validator::extend('minsize', function($attribute, $value, $parameters)
{
return strlen($value) >= $parameters[0];
});
And do the same with maxsize.

Categories