Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

muuucho's avatar
Level 11

Validation problem

I am validating an invoice form and need to apply aconditional rule for the field pay_date: If the variable $status == attested then pay_date shall pass validation if it is empty or is a valid date. If $status != attested then pay_date must be empty to pass validation. How can I achieve that? ($status is created just before validation and is nota filed in the form)

0 likes
3 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To achieve the conditional validation for the pay_date field based on the $status variable, you can use Laravel's Validator class with a custom rule. Here's how you can implement this:

Explanation:

  1. Custom Validation Rule: We define a custom validation rule using a closure. This allows us to apply logic based on the $status variable.

  2. Condition for 'attested' Status: If $status is 'attested', the pay_date can be either empty or a valid date. We check if the pay_date is not empty and is a valid date using strtotime.

  3. Condition for Other Statuses: If $status is not 'attested', the pay_date must be empty. We check if the pay_date is not empty and fail the validation if it is.

  4. Validation Execution: We use Laravel's Validator::make to apply the rules to the data. If validation fails, we return the errors; otherwise, we return a success message.

This approach allows you to dynamically apply validation rules based on the $status variable.

Shivamyadav's avatar

Try this

public function rules()
{
    $invoice = request()->route('invoice');
    $status = $invoice->status;

    return [
        'pay_date' => [
            'bail',
            function ($attribute, $value, $fail) use ($status) {
                if ($status === 'attested') {
                    // If status is 'attested', pay_date can be empty or a valid date
                    if (!empty($value) && !strtotime($value)) {
                        $fail('The ' . $attribute . ' must be a valid date when status is attested.');
                    }
                } else {
                    // If status is not 'attested', pay_date must be empty
                    if (!is_null($value) && trim($value) !== '') {
                        $fail('The ' . $attribute . ' must be empty when status is not attested.');
                    }
                }
            },
        ],
    ];
}

Please or to participate in this conversation.