简体   繁体   中英

Require a field if other field has value

I have 3 field which is bank_name , account_name and account_number . How can I require other two fields if one of them has value? my validation for now looks like this:

validate = [
    'account_name' => ['sometimes','nullable', 'max:50'],
    'bank_name' => ['sometimes','nullable', 'max:50'],
    'account_number' => ['sometimes','nullable', 'max:50'],
];

How can I possibly attain this one?

You can use required_with :

$validate = [
    'account_name' => ['sometimes','nullable', 'max:50', 'required_with:bank_name,account_number'],
    'bank_name' => ['sometimes','nullable', 'max:50', 'required_with:account_name,account_number'],
    'account_number' => ['sometimes','nullable', 'max:50', 'required_with:account_name,bank_name'],
];

With the rules above, when one of the 3 fields has a value, the two other ones would be required.

For more information: https://laravel.com/docs/5.8/validation#rule-required-with

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM