使用单选按钮进行条件验证,如果单选按钮值为yes,则需要另一个输入,否则可以为空

时间:2018-12-31 07:28:07

标签: laravel validation radio-button

我有两个单选按钮,分别为value =“ YES”和value =“ NO”。如果所选单选按钮的值为YES,我想输入下一个输入文本,否则下一个输入文本可以为空

我已经尝试过了 Laravel Validation If checkbox ticked then Input text is required? 但是我认为这仅在复选框上有效,并且不能与单选按钮一起使用。这是我的代码:

查看

            <table>
                <tr>
                    <td><b>If yes, student agree to the accommodation prepared by International Office</b></td>
                    <td><input  type="radio" name="opt_acc" size="20" value="YES"/> YES</td>
                </tr>

                <tr>
                    <td><b>If no, please state where you plan to stay in Indonesia:</b></td>
                    <td><input type="radio" name="opt_acc" size="20" value="NO"/> NO</td>
                </tr>
                    <td><b>Address</b><hr>
                        <input placeholder="Address" type="text" name="address_acc" size=50"></td>
                    <td><b>Contact Person (Name/Phone)</b><hr>
                        <input placeholder="Name & Phone" type="text" name="cp_acc" size="25"></td>

            </table>

验证规则

 public function rules()
{
    return [
      // Accomodation
        'opt_acc' => 'required|in:YES,NO',
        'address_acc' => 'required|string',
        'cp_acc' => 'required|string'
    ];
}

我希望流程如下:

 if (opt_acc == YES) {
     'address_acc' => 'required|string',
     'cp_acc' => 'required|string'
  }
  else {
  'address_acc' => 'nullable|string',
  'cp_acc' => 'nullable|string'
  }

1 个答案:

答案 0 :(得分:2)

您可以编写此内容。希望这能解决您的问题

public function rules()
{
    return [
        'opt_acc' => 'required|in:YES,NO',
        'address_acc' => 'sometimes|nullable|required_if:opt_acc,YES|string',
        'cp_acc' => 'sometimes|nullable|required_if:opt_acc,YES|string'
    ];
}