'Enum values validate on Livewire
Could I use below validation way or similar of Laravel in Livewire?
Validator::make($data, [
'zones' => [
'required',
Rule::in(['first-zone', 'second-zone']),
],
]);
or
starts_with:foo,bar,...
Current code didn't work correctly, during in the testing it just passed when I revised a html value by Chrom Inspection.
View
...
<input wire:model=size type="radio" value="BICYCLE" name="BICYCLE"/>
<input wire:model=size type="radio" value="CAR" name="CAR"/>
<input wire:model=size type="radio" value="CAR" name="BOAT"/>
...
<button wire:click="checkVehicle">Check</button>
---
Livewire Component
public function checkVehicle()
{
$this->validate([
'size' => 'required|string|starts_with:BICYCLE,CAR,BOAT'
]);
}
Solution 1:[1]
If you use php8.1 and up with backed enums you can use the Enum Validation rule, it is available in laravel 8.x and up
use App\Enums\Zones;
use Illuminate\Validation\Rules\Enum;
class ZoneForm extends \Livewire\Component
{
protected function rules() : array
{
// The value 'status' is required and must be defined in the Zones enum
return $request->validate([
'status' => ['required', new Enum(Zones::class)],
]);
}
/** ... */
}
Example how the Zones enum could look
namespace App\Enums;
enum Zones: string
{
case FirstZone = 'first-zone';
case SecondZone = 'second-zone';
}
Solution 2:[2]
You need to use rules() as a method instead of property
use Illuminate\Validation\Rule;
public function rules()
{
return [
'zones' => ['required', Rule::in(['first-zone', 'second-zone'])],
];
}
public function checkVehicle()
{
$this->validate();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Arne_ |
| Solution 2 | Digvijay |
