vendredi 10 février 2017

Validating fields conditionally using Laravel

I have the following validation rules for Laravel:

return [
    'offer_type' => 'required|in:permanent,temporary',
    'start_date' => 'required_if:offerType,temporary|date_format:d/m/Y',
    'end_date' => 'required_if:offerType,temporary|date_format:d/m/Y|after:start_date',
];

Basically, if the offer_type is temporary, a start_date and end_date is required and must follow the d/M/Y format. Also, the end_date must be after the start_date.

If the offerType is permanent, there is no need to validate start_date or end_date as they are not even used.

The issue I have is that it if the user sends data like the following:

  • offerType: permanent
  • startDate: foo
  • endDate: bar

Then Laravel will raise a validation error, even though start_date and end_date does not need to be validated, as the offer type is permanent.

How can I make Laravel only validate start_date and end_date if offer_type is temporary.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire