使用IN规则的Laravel数组验证

时间:2018-10-02 12:53:30

标签: laravel

我正在尝试使用IN验证规则来验证多选表单的值。尽管与列表中的选项之一相同,但我仍然收到错误消息,指出我的值不正确。我认为这必须是我在验证器中标识名称的方式(“ step1”)。但是,我还使用了step1。,step1.0。,step1 *。它将继续给出与IN错误相对应的“无效响应”响应。

控制器

public function postQuestionDetailsStep1(Request $request)
{
    if ($request->ajax())
    {
        $step1 = $request->input('step1');

        $this->validate($request, [
            'step1' => 'required',
            'step1.0' => 'in:Less than $50,000,$50,000-$100,000,More than $100,000',
        ], [
            'step1.required' => 'You must choose one.',
            'step1.in' => 'Invalid response.',
        ]);
    }
}

查看

<input type="checkbox" class="custom-control-input" id="step1-option1" name="step1[]" value="Less than $50,000">
<input type="checkbox" class="custom-control-input" id="step1-option2" name="step1[]" value="$50,000-$100,000">
<input type="checkbox" class="custom-control-input" id="step1-option3" name="step1[]" value="More than $100,000">

JavaScript

$('#step-1').submit(function(e) {
    e.preventDefault();

    var step1 = [];

    $("input[name='step1[]']:checked").each(function() {            
        step1.push($(this).val());
    });

    $.ajax({
        type: "POST",
        url: "/question/details/1",
        data: {step1:step1},
        error: function(data){
        },
        success: function(data) {
            console.log(data);
        }
    });
});

1 个答案:

答案 0 :(得分:1)

您的in规则中的逗号将您要创建的数组弄乱了。 Laravel将像这样读取您的数组:

['Less than $50', '000', '$50', '000-$100', '000', 'More than $100', '000']

您可以将规则更改为以下内容,以解决逗号问题:

in:Less than $50,000,$50,000-$100,000,More than $100,000'

Rule::in(['Less than $50,000', '$50,000-$100,000', 'More than $100,000']);

请确保use Rule类:

use Illuminate\Validation\Rule;