Search code examples
phplaravelvalidationlaravel-validation

Combine required, sometimes and regex in validation


I want to implement the following logic:

  • The field bank_info_zip is required if bank_info_contact_last_name or bank_info_street or bank_info_city has any characters.
  • If it contains any chars, it should get matched against the pattern: \d{5}
  • It should not get matched against the pattern if it is empty.

This is my validation-expression/rule:

"bank_info_zip" => "required_with:bank_info_contact_last_name,bank_info_street,bank_info_city|regex:/\d{5}/"

I have tried to add sometimes but dont understand how that works with required as it seems to do the exact opposite/negate its effect.

The example in the docs is this:

$v = Validator::make($data, [
    'email' => 'sometimes|required|email',
]);

and it makes me question my ability to think logically even more.


Solution

  • request()->validate([
        'bank_info_zip' => [
            'required_with:bank_info_contact_last_name,bank_info_street,bank_info_city',
            \Illuminate\Validation\Rule::when(request()->bank_info_zip, ['regex:/\d{5}/'])
        ],
    ]);
    

    Resources:

    1. Conditional Validation Rules

    2. required_with:foo,bar,...