带复选框的 Laravel 验证

I'l*_*ack 1 php laravel laravel-5 laravel-5.3

如果use_shipping未选中且用户未在shipping_note- 验证中输入值,则验证应该已通过但失败了?

<input type="hidden" name="use_shipping" value="0">
<input type="checkbox" name="use_shipping" value="1" {{ old('use_shipping', $delivery->use_shipping) ? 'checked="checked"' : '' }}>
Run Code Online (Sandbox Code Playgroud)

文本

<input type="text" name="shipping_note" value="">
Run Code Online (Sandbox Code Playgroud)

在 Laravel 请求类中:

public function rules()
{

    return [
        'use_shipping'  => 'boolean',
        'shipping_note' => 'required_with:use_shipping',
    ];
}
Run Code Online (Sandbox Code Playgroud)

pat*_*cus 5

验证required_with指出:

仅当任何其他指定字段存在时,验证字段才必须存在且不为空。

由于您的隐藏输入,该shipping_note字段将始终存在。由于即使未选中该复选框,该字段仍然存在,因此required_with始终会触发验证。

您最有可能正在寻找的是required_if验证,其中指出:

required_if:另一个字段,值,...

如果anotherfield字段等于任何值,则验证中的字段必须存在且不为空。

public function rules()
{
    return [
        'use_shipping'  => 'boolean',
        'shipping_note' => 'required_if:use_shipping,1',
    ];
}
Run Code Online (Sandbox Code Playgroud)

这应该导致shipping_note仅当值为use_shippingis时才需要1,这应该仅在选中复选框时发生。