0

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!

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

'repeat_day' => 'nullable',

insert this inside of your request validation

1 Comment

The validation should fail, this will cause it to accept null which is already the case at the moment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.