skip to Main Content

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>
...

3

Answers


  1. Chosen as BEST ANSWER

    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.


  2. 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'
    ]
    
    Login or Signup to reply.
  3. 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 )

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search