Laravel 9 required_if not validating - php

I'm using Laravel 9 and Livewire 2.0
I have an integer field called 'new_weight' that should validate required if the boolean checkbox 'stripped' is selected. Although 'stripped' is not selected, it's still validating as required. The validation $rules are being hit because if I remove the rule, it doesn't validate at all.
I also recently noticed that if I die and dump '$this->stripped' when the checkbox is selected, it dumps 'true' to the console and not '1', but if I leave unchecked, it dumps '0'--not sure if this matters.
edit.php
...
protected $rules = [
'car_color' => 'required|string',
'new_weight' => 'required_if:stripped,accepted|integer|min:1|max:999',
];
protected $messages = [
'car_color' => 'Please enter car color.',
'new_weight' => 'New Weight Value must be great than 1 but less than 999'
];
...
edit.blade.php
...
<div class="flex items-center h-5">
<input wire:model.defer="stripped" id="stripped" name="stripped"
wire:click="updateStripped"
type="checkbox">
</div>
<div>
<input wire:model.defer="new_weight" id="new_weight" name="new_weight"
type="text"
placeholder="New Vehicle Weight in lbs:">
</div>
...

Since stripped itself is not a rule, I would consider using a custom callback to evaluate the stripped input.
'new_weight' => [
Rule::requiredIf(function () use ($request) {
return $request->input('stripped');
}),
'integer|min:1|max:999'
]

I have this problem too, so I use Rule::when like this and get me same result:
[Rule::when(this->stripped == 'accepted', 'required|integer|min:1|max:999')]
when condition ( this->stripped == 'accepted' ) is true, the rules run
of course if stripped is a check box, you must find out what that's return, so first use dd for that, then replace that with 'accepted' ( I think check box return true and false )

The new_weight field had a default null value in the database. Once I re-migrated with a default empty value, my problem was solved.

Related

How to get the validation message in laravel-validation-rules/credit-card

I used the laravel validator for credit card information as per instructed here.
I can finally let it work but my problem is how can I make its result readable by a user. I am also using Laravel validation like this:
public static function validate()
{
$val = [
'card_num' => ['required', 'numeric', new CardNumber],
];
return $val;
}
So, if I clicked the submit button and the field is empty, the result is card numは必須です。 which means card number is required. And if I supply an invalid card number, the result is validation.credit_card.card_length_invalid, how can I make it has the same result as leaving the field empty? I do like this when getting the validation errors in blade php.
<div>
<label>カード番号</label>
<input type="text" name="card_num" id="credit-card" value="{{ old('card_num', $user['card_num']) }}" >
</div>
#if ($errors->has('card_num'))
<p class="alert-error">
{{ $errors->first('card_num') }}
</p>
#endif
UPDATE
I have seen its source file and messages, but I don't want to directly change the vendor files.
I have tried adding the custom in validation.php, but it's not working.
'custom' => [
'validation.card_length_invalid' => '無効なカード長',
'validation.credit_card' => 'クレジットカード',
],
Your array in validation.php is close to correct. Try changing the top-level key to credit_card instead of custom like they have in the source code. I'm not 100% sure, but I don't think this package supports messages in the custom array like the ordinary Laravel rules do. For example:
'credit_card' => [
'card_length_invalid' => '無効なカード長',
'credit_card' => 'クレジットカード',
],

Laravel 5.6: Skip validation step if field exists and isn't changed. If field IS changed it is Required - but not unique

I have situation where an admin edits an employee form: The first name, last name, and SSN are required on ADDING an employee. No problems there. Where I have an issue is when EDITING the form. I have no problem validating the SSN as it is a unique field.
'ssn_edit' => 'required|unique:employees,ssn,' . $id
But what I DO have an issue with is the non-unique fields. I don't know how to set the validation to skip by ID when the field is NOT unique. Here is the entire rules section of the FormRequest:
public function rules()
{
$id = $this->input('employee_id');
return [
'first_name' => 'required',
'last_name' => 'required',
'ssn_edit' => 'required|unique:employees,ssn,' . $id
];
}
Obviously - this throws the validation error on first_name and last_name regardless if the field is populated or not.
Any help some of you Laravel gurus can throw my way would be GREATLY appreciated!
There is so many tricks you can do to solve the problem. But I only got two ways..
The first is: Prevent to send your ssn_edit value when you want to edit the employee
example:
<input type="text" value="{{ isset($employee) ? $employee->ssn_edit : old('ssn_edit') }}" #isset($employee) disabled #endisset name="ssn_edit">
public function rules()
{
$id = $this->input('employee_id');
return [
'first_name' => 'required',
'last_name' => 'required',
'ssn_edit' => 'required|sometimes|unique:employees,ssn,' . $id
];
}
The second is: Check your method before validate the employee.. is it POST or PUT, if it's PUT don't add the unique rule in your validation.
Conclusion: The validation will work every time you call the validation, no matter if you edit or add new employee. #CMIIW
You mustn't have error with validating non-unique fields, probably you have wrong edit form, set value attribute to input like
<input type="text" value="{{ $employee->first_name }}" name="first_name">

Laravel Validation Rules If Value Exists in Another Field Array

I am working in Laravel 5.4 and I have a slightly specific validation rules need but I think this should be easily doable without having to extend the class. Just not sure how to make this work..
What I would like to do is to make the 'music_instrument' form field mandatory if program array contains 'Music'.
I found this thread How to set require if value is chosen in another multiple choice field in validation of laravel? but it is not a solution (because it never got resolved in the first place) and the reason it doesn't work is because the submitted array indexes aren't constant (not selected check boxes aren't considered in indexing the submission result...)
My case looks like this:
<form action="" method="post">
<fieldset>
<input name="program[]" value="Anthropology" type="checkbox">Anthropology
<input name="program[]" value="Biology" type="checkbox">Biology
<input name="program[]" value="Chemistry" type="checkbox">Chemistry
<input name="program[]" value="Music" type="checkbox">Music
<input name="program[]" value="Philosophy" type="checkbox">Philosophy
<input name="program[]" value="Zombies" type="checkbox">Zombies
<input name="music_instrument" type="text" value"">
<button type="submit">Submit</button>
</fieldset>
</form>
If I select some of the options from the list of check boxes I can potentially have this result in my $request values
[program] => Array
(
[0] => Anthropology
[1] => Biology
[2] => Music
[3] => Philosophy
)
[music_instrument] => 'Guitar'
Looking at validation rules here: https://laravel.com/docs/5.4/validation#available-validation-rules I think something like his should work but i am literally getting nothing:
$validator = Validator::make($request->all(),[
'program' => 'required',
'music_instrument' => 'required_if:program,in:Music'
]);
I was hoping this would work too but no luck:
'music_instrument' => 'required_if:program,in_array:Music',
Thoughts? Suggestions?
Thank you!
Haven't tried that, but in general array fields you usually write like this: program.*, so maybe something like this will work:
$validator = Validator::make($request->all(),[
'program' => 'required',
'music_instrument' => 'required_if:program.*,in:Music'
]);
If it won't work, obviously you can do it also in the other way for example like this:
$rules = ['program' => 'required'];
if (in_array('Music', $request->input('program', []))) {
$rules['music_instrument'] = 'required';
}
$validator = Validator::make($request->all(), $rules);
I know this post is older but if someone came across this issue again.
$validator = Validator::make($request->all(),[
'program' => 'required',
'music_instrument' => 'required_if:program,Music,other values'
]);
You could create a new custom rule called required_if_array_contains like this...
In app/Providers/CustomValidatorProvider.php add a new private function:
/**
* A version of required_if that works for groups of checkboxes and multi-selects
*/
private function required_if_array_contains(): void
{
$this->app['validator']->extend('required_if_array_contains',
function ($attribute, $value, $parameters, Validator $validator){
// The first item in the array of parameters is the field that we take the value from
$valueField = array_shift($parameters);
$valueFieldValues = Input::get($valueField);
if (is_null($valueFieldValues)) {
return true;
}
foreach ($parameters as $parameter) {
if (in_array($parameter, $valueFieldValues) && strlen(trim($value)) == 0) {
// As soon as we find one of the parameters has been selected, we reject if field is empty
$validator->addReplacer('required_if_array_contains', function($message) use ($parameter) {
return str_replace(':value', $parameter, $message);
});
return false;
}
}
// If we've managed to get this far, none of the parameters were selected so it must be valid
return true;
});
}
And don't forget to check there is a use statement at the top of CustomValidatorProvider.php for our use of Validator as an argument in our new method:
...
use Illuminate\Validation\Validator;
Then in the boot() method of CustomValidatorProvider.php call your new private method:
public function boot()
{
...
$this->required_if_array_contains();
}
Then teach Laravel to write the validation message in a human-friendly way by adding a new item to the array in resources/lang/en/validation.php:
return [
...
'required_if_array_contains' => ':attribute must be provided when ":value" is selected.',
]
Now you can write validation rules like this:
public function rules()
{
return [
"animals": "required",
"animals-other": "required_if_array_contains:animals,other-mamal,other-reptile",
];
}
In the above example, animals is a group of checkboxes and animals-other is a text input that is only required if the other-mamal or other-reptile value has been checked.
This would also work for a select input with multiple selection enabled or any input that results in an array of values in one of the inputs in the request.
The approach I took for a similar problem was to make a private function inside my Controller class and use a ternary expression to add the required field if it came back true.
I have roughly 20 fields that have a checkbox to enable the input fields in this case, so it may be overkill in comparison, but as your needs grow, it could prove helpful.
/**
* Check if the parameterized value is in the submitted list of programs
*
* #param Request $request
* #param string $value
*/
private function _checkProgram(Request $request, string $value)
{
if ($request->has('program')) {
return in_array($value, $request->input('program'));
}
return false;
}
Using this function, you can apply the same logic if you have other fields for your other programs as well.
Then in the store function:
public function store(Request $request)
{
$this->validate(request(), [
// ... your other validation here
'music_instrument' => ''.($this->_checkProgram($request, 'music') ? 'required' : '').'',
// or if you have some other validation like max value, just remember to add the |-delimiter:
'music_instrument' => 'max:64'.($this->_checkProgram($request, 'music') ? '|required' : '').'',
]);
// rest of your store function
}
Here my piece of code to solve that kind of trouble usind Laravel 6 Validation Rules
I tried to use the code above
public function rules()
{
return [
"some_array_field.*" => ["required", "integer", "in:1,2,4,5"],
"another_field" => ["nullable", "required_if:operacao.*,in:1"],
];
}
I need that when some_array_field has 1 in your value, another_field must be validated, otherwhise, can be null.
With the code above, doesn't work, even with required_if:operacao.*,1
If I change the rule for another_field to required_if:operacao.0,1 WORKS but only if the value to find is in index 0, when the order changes, validation fails.
So, I decided to use a custom closure function
Here's the final code for the example that works fine form me.
public function rules()
{
return [
"some_array_field.*" => ["required", "integer", "in:1,2,4,5"],
"another_field" => [
"nullable",
Rule::requiredIf (
function () {
return in_array(1, (array)$this->request->get("some_array_field"));
}
),
]
];
}
I hope that solve your trouble too!

Laravel validation for field if "image/file" is selected?

I have a field "image", type is file and need only to validate if image is selected, means it can be also empty.
I tried it so: 'avatar' => 'mimes:jpeg,jpg,png,gif|max:100000', but so it is also required.
I tried still with parameters present and sometimes but the field is still required.
How can I validate it only if image is selected?
If the "avatar" field may not be present in the input array you want to use:
'avatar' => 'sometimes|mimes:jpeg,jpg,png,gif|max:100000'
In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule.
If the "avatar" field will absolutely be in the input array and it's value will be then null you want to use:
'avatar' => 'nullable|mimes:jpeg,jpg,png,gif|max:100000'
The field under validation may be null. This is particularly useful when validating primitive such as strings and integers that can contain null values. To quickly accomplish this, add the nullable rule.
In your case, You have to check only if it is present or not null - Validating When there is value. So use sometimes
"In some situations, you may wish to run validation checks against a
field only if that field is present in the input array. To quickly
accomplish this, add the sometimes rule to your rule list"
$v = Validator::make($data, array(
'email' => 'sometimes|required|email',
));
In your case,
$v = Validator::make($data, array(
'avatar' => 'sometimes|mimes:jpeg,jpg,png,gif|max:100000',
));
Note:
The following code will do nothing because there are no rules to validate against, done because even if it's present in the POST array, you should specify rules. and the doesn't make any difference.
$v = Validator::make($data, array(
'avatar' => 'sometimes',
));
You could try 'nullable' in your rules.
https://laravel.com/docs/5.3/validation#rule-nullable
First check the $request object. Check avatar is available or not in your request. Then try this:
'avatar' => 'sometimes|image|mimes:jpeg,bmp,png,gif|max:2048'
the solution i found that works best is using Rule::requiredIf
'cover' => [
'image',
Rule::requiredIf(function () {
if (some_condition) {
return false;
}
return true;
})
]

How to make Request default in Laravel 5.1 when none is given

I am using Laravel 5.1 and I need to make a default value when in field is none given.
So the view looks like:
<form name="search" method="POST" action="/s">
Country<input name="country" type="text">
Field<input name="field" type="text">
<button type="submit" type="button">Search</button>
<input name="_token" value="{{ csrf_token() }}" type="hidden">
</form>
The controller looks like:
public function extendedPost(Request $request){
$data = $request->all();
$request->input('field', 'Random');
dd($data);
}
In Laravel 5.1 Documentation we have:
You may pass a default value as the second argument to the input
method. This value will be returned if the requested input value is
not present on the request:
$name = $request->input('name', 'Sally');
So when I have something in "Field" I have:
array:21 [▼
"country" => ""
"field" => "dddd"
"_token" => "XeMi"
]
But when the "Field" is empty I have
array:21 [▼
"country" => ""
"field" => ""
"_token" => "XeMi"
]
Instead of
array:21 [▼
"country" => ""
"field" => "Random"
"_token" => "XeMi"
Thanks for helping me
Very late answer here, but hopefully still useful clarification.
You may pass a default value as the second argument to the input
method. This value will be returned if the requested input value is
not present on the request:
This means the second argument will be used if the input isn't present. But if this comes from an optional field in a form, then the input IS present - with the value of an empty string.
That means that
$name = $request->input('name', 'Sally');
Will return "Sally" when there is no name field submitted by the form, but will return "" if the user leaves the name field blank.
If we want the value of 'Sally' when the field was blank, we can do as Zakaria suggests and use:
if( $request->has('field')) {
$request->field = 'Random';
}
... but that will very quickly become messy if you have a lot of fields that all need to be checked.
Another option is to use the ternary operator. Something like:
$yourValue = $request->has('field') ? $request->input('field') : 'Random';
$yourValue2 = $request->has('country') ? $request->input('country') : 'Australia';
It's a mouthful, but allows you to write each value out on its own line.
Your $request variable still won't show these fields. If you are planning to check for the field multiple times, then you can either assign a value to $request like in Zakaria's answer, or you can set it in a variable that you will check.
In many cases, you want to assign the input to something, in which case you can use the ternary operator directly when you're assigning it.
For example, if we're setting the country field for the current user, we might use:
$user->country = $request->has('country') ? $request->input('country') : 'Unspecified';
Often, it's easier to bypass the problem. Some other options might be:
When using an optional select dropdown, you can set the "empty" default value to have a value when it's submitted. For example, in a country dropdown you might start with:
<select name="country">
<option value="unspecified" selected="selected></option>
<option>Australia</option>
<option>Brazil</option>
<option>Canada</option>
</select>
Set fields as required in the form. And verify that a value was submitted using request validation.
$this->validate(request(), [
'field' => 'required',
'country' => 'required:min:3',
]);
That will return to the form with an $errors collection that can be used to display a message to the user. Put this first, and by the time you need to use the input, the validation has already checked that they submitted something.
The function input not updating the $request it will just check if the given attribute is not present in Request if so it will return default value passed in second argument, try to use has() to check if the attribute is present in request and then update the request manually :
if( $request->has('field')) {
$request->field = 'Random';
}
Note : The has method returns true if the value is present and is not an empty string.
Hope this helps.
In my case, request()->country = 'default' or $request->country = 'default'; does not work as validation rule still throws out error for the missing field. But $request['country'] = 'default' does the trick.

Categories