【问题标题】:Laravel Array Validation Using IN RuleLaravel 数组验证使用 IN 规则
【发布时间】:2018-10-02 21:18:54
【问题描述】:

我正在尝试使用 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);
        }
    });
});

【问题讨论】:

  • 你使用的是什么版本的 Laravel?
  • 5.6,我相信......
  • 由于您的规则选项也有逗号,您是否尝试使用双引号:in:"Less than $50,000","$50,000-$100,000","More than $100,000"?参考:stackoverflow.com/questions/19575860/…

标签: laravel


【解决方案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;

【讨论】:

  • 它让我无法在验证中使用 Rule 类。但是,这有效。谢谢!
猜你喜欢
  • 2017-07-09
  • 2018-10-25
  • 2018-04-24
  • 1970-01-01
  • 2015-11-20
  • 1970-01-01
  • 1970-01-01
  • 2016-11-26
  • 2019-07-25
相关资源
最近更新 更多