Reputation: 176
I have a array of states that is looping in the front-end. I want to validate in the backend that the value is inside the array. I keep getting error that The selected state is invalid.
Blade View
<select wire:model.defer="state" name="state">
@foreach($states as $state)
<option value="{{ $state }}">{{ strtoupper($state) }}</option>
@endforeach
</select>
Controller (Livewire)
public $states = [
'sa', 'vic', 'nsw', 'qld', 'act', 'nt', 'wa', 'tas'
];
protected function rules()
{
$array = [
'state' => 'required|in:$this->states',
];
return $array;
}
Upvotes: 1
Views: 1957
Reputation: 121
Or if your just looking for a basic validation method/function for states, it's really just a string validation helper regardless of the framework. Here we use U.S. state codes. The principle is the same.
/**
* Validate State code strings
*
* @return boolean
*/
public function getValidStates($str) {
$states = array(
"AL","AK","AZ","AR","CA","CO","CT","DE","DC","FL","GA","HI",
"ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN",
"MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH",
"OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA",
"WV","WI","WY","AS","GU","MP","PR","VI","FM","MH","PW"
);
if (in_array(strtoupper($str), $states)) {
return true;
}
return false;
}
Upvotes: 0
Reputation: 15319
Try this
protected function rules()
{
$array = [
'state' => 'required|in:'.implode(',',$this->states),
];
return $array;
}
or
protected function rules()
{
$array = [
'state' => ['required',Rule::in($this->states)],
];
return $array;
}
Ref:https://laravel.com/docs/8.x/validation#rule-in
Upvotes: 3