首页 > 解决方案 > 如果在 laravel 中选中了特定的复选框,如何要求一个字段?

问题描述

我是 Laravel 的新手,我有三个复选框:WhatsApp、电子邮件和 SMS

我想在验证 CustomerRequest 中完成的是,如果选中了电子邮件复选框,则需要电子邮件字段:

以下是我的规则示例:

public function rules()
    {
        return [
            'choix' => 'required',
            'tel' => 'required|max:25',
            'contract' => 'required|numeric|max:9',
            'nom' => 'required|max:255',
            'email' => 'required|max:50',
            'language' => 'required|max:2',
            'g-recaptcha-response' => 'required|captcha',
            'conditionAccepted' => 'accepted',
        ];
    }

下面是我的复选框字段:

 <div class="form-group row">
                    <div class="col-md-12 " style="text-align : left; margin-left:20px;" ><label class="checkbox-inline check"> <input type="checkbox" class="checkbox" name="choix[]" value="WHA">
                            <span style="margin-top:10px; margin-left:20px; position: absolute;">WhatsApp</span></label></div>
                    <div class="col-md-12 " style="text-align : left; margin-left:20px;" ><label class="checkbox-inline check"> <input type="checkbox" class="checkbox" name="choix[]" value="SMS">
                            <span style="margin-top:10px; margin-left:20px; position: absolute;">SMS</span></label></div>
                    <div class="col-md-12 " style="text-align : left; margin-left:20px;" ><label class="checkbox-inline check"> <input type="checkbox" class="checkbox" name="choix[]" value="MAIL">
                            <span style="margin-top:10px; margin-left:20px; position: absolute;">Email</span></label></div>

                </div>

感谢指导

标签: laravel

解决方案


我能够使用以下代码解决问题:

'choix.*' => 'in:WHA,SMS,MAIL',
'tel' => 'required|max:25',
'contract' => 'required|digits:9|exists:accounts,sic_code',
'nom' => 'required|max:255',
'email' => 'required_if:choix.MAIL,==,MAIL|nullable|email|max:50',
'language' => 'required|max:2',
'g-recaptcha-response' => 'required|captcha',
'conditionAccepted' => 'accepted',

推荐阅读