【问题标题】:How to require a field if a particular checkbox is checked in laravel?如果在 laravel 中选中了特定的复选框,如何要求一个字段?
【发布时间】:2023-03-25 08:59:01
【问题描述】:

我是 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>

感谢指导

【问题讨论】:

  • 这能回答你的问题吗? required_if Laravel 5 validation
  • 嗨@Don'tPanic,我试过'email' =&gt; 'required_if:choix,==,MAIL|max:50',,但它不起作用。可能是什么问题?

标签: laravel


【解决方案1】:

您可以使用required_with 验证规则。检查文档中的整个列表,有许多有用的验证规则https://laravel.com/docs/5.8/validation#rule-required-unless

【讨论】:

    【解决方案2】:

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

    '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',
    

    【讨论】:

      猜你喜欢
      • 2012-09-14
      • 1970-01-01
      • 2014-09-14
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多