Reputation: 964
Currently making API endpoints for repetition schedule, but I am having an issue in validating array to make sure it exists in the preset array:
For example, the repeat_day
values must have correct days
This is the API request:
{
"repeat_by": "daily",
"repeat_day": [
"Sunday",
"xxx"
],
"repeat_date": [],
"repeat_week": [],
"repeat_month": []
}
This is the StoreUpdateScheduleRequest
public function __construct()
{
$this->dayArray = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
//and some other array
}
public function rules()
{
$repeatDayRule = request()->get('repeat_by') == "daily" ? ['required', Rule::in($this->dayArray)] : '';
//and some other validation rules
return [
"repeat_day.*" => $repeatDayRule
"repeat_date.*" => $repeatDateRule
"repeat_week.*" => $repeatWeekRule
"repeat_month.*" => $repeatMonthRule
];
}
My problem is that, when I provide null
or empty array, the validation passes which it should fail.
{
"repeat_by": "daily"
"repeat_day": null //or even []
}
Note:
I tried making validation to request_day
instead of request_day.*
, but it does not validate the day properly.
Would like to use Laravel built in validation (maybe I am missing something), and not looking to extend the validation.
Thanks in advance! Cheers!
Upvotes: 0
Views: 731
Reputation: 60
'repeat_day' => 'nullable',
insert this inside of your request validation
Upvotes: 0
Reputation: 3419
You should implement both rules when validating that array with the filled
rule. Something like this:
return [
"repeat_day" => 'array|filled',
"repeat_day.*" => $repeatDayRule,
"repeat_date" => 'array|filled',
"repeat_date.*" => $repeatDateRule,
"repeat_week" => 'array|filled',
"repeat_week.*" => $repeatWeekRule,
"repeat_month" => 'array|filled',
"repeat_month.*" => $repeatMonthRule
];
With this code you will check that, for example, repeat_day
is an array and it's filled. With the next sentence you will check that its values are valid with the $repeatDayRule
Upvotes: 1