Validate value 0 and range based validation in Lumen - php

I want to perform following validation on my textfield using Lumen Validation:
The value must be greater than 0 and less than or equal to 100
My current code is:
$validator = Validator::make($params, [
'weight' => 'required'
]);
if ($validator->fails()) {
$messages = $validator->errors();
$message = $messages->first();
return $message;
exit;
}

You can use the between validation rule to check this. The parameters are inclusive.
You also need to add in the numeric validation rule so that between will know to check if the numeric value is between the supplied values. Without the numeric validation, it would validate the length of the string, not the numeric value of it.
$validator = Validator::make($params, [
'weight' => 'required|numeric|between:1,100'
]);

Related

Using excludes_unless validation rule with arrays in Laravel

Laravel's exclude_unless,field,value rule doesn't seem to work in the instance where field is an array of values and value is contained within the field array.
Given the following:
$validator = Validator::make($request->all(), [
'some_array' => 'array',
'some_field' => 'exclude_unless:some_array,foo|alpha_num',
]);
Where some_array is equal to ['foo'], the validator will fail to exclude some_field. This seems to be because the comparison that lies beneath excludes_unless is in_array(['foo'], ['foo']) which returns false.
Is it possible to achieve the same logic of exclude_unless — excluding a field from validation if another field equals a certain value, but where the field being compared against is an array and we're checking that the value is in that array?
As long as you're using Laravel 8.55 or above, you could use Rule::when():
use Illuminate\Validation\Rule;
$someArray = $request->input('some_array', []);
$validator = Validator::make($request->all(), [
'some_array' => 'array',
'some_field' => Rule::when(!empty(array_intersect(['foo'], $someArray)), ['exclude']),
]);

validate array or an array of integers in Laravel

I have a input request that can be an integer or an array of integer values.
How can I check validation of that in Laravel? I'm using Laravel 5.5.I know that there is a simple array validation rules that checks an input is an array or not:
array
The field under validation must be a PHP array.
Is there any predefined validation rule or should I write a new one? if yes, How?
$input = $request->all();
//Check if input param is an array
if(is_array($input['item']))
{
//Array validator
$Validator = Validator::make($input,
[
'item' => 'required', //Array with key 'item' must exist
'item.*' => 'sometimes|integer', //All values should be integers
]);
}
else
{
//Integer validator
$Validator = Validator::make($input,
[
'item' => 'required|integer',
]);
}
Use sometimes it applies validation rule only if that input parameter exist. Hope this helps

Laravel 5.2 validator: Validate Array request parameter, at least one value must be selected

I am having a form where i am having title, body, answers[][answer] and options[][option].
I want atleast one answer must be selected for the given question, for example:
i have ABC question and having 5 options for that question,now atleast one answer must be checked or all for given question.
Efforts
protected $rules = [
'title' => 'required|unique:contents|max:255',
'body' => 'required|min:10',
'type' => 'required',
'belongsto' => 'sometimes|required',
'options.*.option' => 'required|max:100',
'answers.*.answer' => 'required',
];
But this is not working. i want atleast one answer must be selected.
Please help me.
The problem is that on $_POST an array filled with empty strings will be passed if no answer is selected.
$answers[0][0] = ''
$answers[0][1] = ''
$answers[0][2] = ''
Hence the following will not work since array count will be greater than zero due to the empty strings:
$validator = Validator::make($request->all(), [
'answers.*' => 'required'
]);
The easiest way to solve this is to create a custom Validator rule by using Laravel's Validator::extend function.
Validator::extendImplicit('arrayRequireMin', function($attribute, $values, $parameters)
{
$countFilled = count(array_filter($values));
return ($countFilled >= $parameters[0]);
});
And then call it in your Validation request:
$validator = Validator::make($request->all(), [
'answers.*' => 'arrayRequireMin:1'
]);
The magic happens in array_filter() which removes all empty attributes from the array. Now you can set any minimum number of answers required.
Validator::extendImplicit() vs Validator::extend()
For a rule to run even when an attribute is empty, the rule must imply that the attribute is required. To create such an "implicit" extension, use the Validator::extendImplicit() method:
Laravel's validation docs
Try this,
'answer.0' => 'required'
it will help you. I think.

Validation on custom array - Lumen

How can I perform validation on custom array in Lumen framework. e.g:
Example array:
$params = array('name' => 'john', 'gender' => 'male');
I have tried something like this but didn;t work:
$validator = Validator::make($params, [
'name' => 'required',
'gender' => 'required'
]);
if ($validator->fails()) {
$messages = $validator->errors();
$message = $messages->first();
echo $message;
exit;
}
The validation is passing because the fields are in fact present. Use something like min or maxor size to validate the length of a string.
http://lumen.laravel.com/docs/validation#rule-required
Edit
I stand corrected. The required does actually seem to validate if it contains anything.
Update
To clarify; the code that is supposed to run if $validator->fails() doesn't ever run if the validation passes.

Laravel 4 validation constant pass

I'm using Laravel 4.2.8 and trying to validate the next form:
The first select field is required. And only one is required from the next three fields.
Phone with formatting is the last. And another two are for digits (some IDs).
I validate in controller, the code is next:
public function getApplication()
{
$input = Input::except('_token');
Debugbar::info($input);
$input['phone'] = preg_replace('/[^0-9]/', '', $input['phone']); // remove format from phone
$input = array_map('intval', $input); // convert all numeric data to int
Debugbar::info($input);
$rules = [ // Validation rules
['operation-location' => 'required|numeric'],
['app-id' => 'numeric|min:1|required_without_all:card-id,phone'],
['card-id' => 'numeric|digits:16|required_without_all:app-id,phone'],
['phone' => 'numeric|digits:12|required_without_all:app-id,card-id']
];
$validator = Validator::make($input, $rules);
if ($validator->passes()) {
Debugbar::info('Validation OK');
return Redirect::route('appl.journal', ['by' => 'application']);
}
else { // Validation FAIL
Debugbar::info('Validation error');
// Redirect to form with error
return Redirect::route('appl.journal', ['by' => 'application'])
->withErrors($validator)
->withInput();
}
}
As you may see I convert numeric IDs to integers myself and leave only number for phone number.
The problem is when I submit form as it is, it passes validation, despite one field is required and starter phone format is too short.
I've tried changing required_without_all to just required on all fields (!), but it still passes fine with blank empty form submitted.
And I expect at least one field to be properly filled.
Debug of my inputs.
Initial:
array(4) [
'operation-location' => string (1) "0"
'app-id' => string (0) ""
'card-id' => string (0) ""
'phone' => string (6) "+3 8(0"
]
After conversion to int:
array(4) [
'operation-location' => integer 0
'app-id' => integer 0
'card-id' => integer 0
'phone' => integer 380
]
Posted similar smaller problem to Laravel issues.
I know this sounds weird but I think this is just an issue with your rules array.
You current rules array is an array of arrays. The Validator looks for an array with keys and values. I believe your current rules are being parsed as keys, but with no value. And then the Validator was basically seeing no rules, and it automatically passed. Try this.
$rules = [
'operation-location' => 'required|numeric',
'app-id' => 'numeric|min:1|required_without_all:card-id,phone',
'card-id' => 'numeric|digits:16|required_without_all:app-id,phone',
'phone' => 'numeric|digits:12|required_without_all:app-id,card-id'
];

Categories