Laravel 验证检查字段不为空

Laravel 验证检查字段不为空,laravel,laravel-5.3,Laravel,Laravel 5.3,我们正在尝试验证一个或另一个字段,第二个字段仅在他们选择不填写第一个字段时显示。因此,我们只需要第二个字段来验证第一个字段是否为空 对于检查设备品牌的上下文,我们有一个系统已知的品牌/品牌列表,但如果您的品牌/品牌没有出现,可以选择手动写入。但我们需要验证手动输入字段是否为空,但前提是它们跳过了第一个列表 'single_item_make' => 'required_if:policy_type,single|required_if:single_item_make_other,', '

我们正在尝试验证一个或另一个字段,第二个字段仅在他们选择不填写第一个字段时显示。因此,我们只需要第二个字段来验证第一个字段是否为空

对于检查设备品牌的上下文,我们有一个系统已知的品牌/品牌列表,但如果您的品牌/品牌没有出现,可以选择手动写入。但我们需要验证手动输入字段是否为空,但前提是它们跳过了第一个列表

'single_item_make' => 'required_if:policy_type,single|required_if:single_item_make_other,',
'single_item_make_other' => 'required_if:policy_type,single|required_if:single_item_make,'
我们尝试了上述方法,但没有效果,我们似乎在文档中找不到任何关于检查字段是否为空的信息

一次只能提交这两个字段中的一个。

正如文档所建议的,您需要按如下方式使用它:

'single_item_make' => 'required_if:policy_type,single|required_without:single_item_make_other,',
'single_item_make_other' => 'required_if:policy_type,single|required_without:single_item_make,'

在这种情况下,如果,则不能将
required\u与不带
required\u组合在一起,因为两者冲突

在当前代码中,关于这两个方面的第一条规则是:

required\u如果:策略类型,单个

如果
策略类型==='single'
,则需要两个字段,如果其中一个字段为空,则此验证将失败

解决方案可能是使用复杂的条件验证,如下所示:

$v = Validator::make($data, [
     'policy_type' => [
          'required',
          'in:single,x,y', // ?
     ],
     // some other static validation rules you have
]);

// conditional validation based on policy_type === 'single';
$v->sometimes('single_item_make', 'required_without:single_item_make_other', function ($input) {
    return $input->policy_type === 'single';
});

$v->sometimes('single_item_make_other', 'required_without:single_item_make', function ($input) {
    return $input->policy_type === 'single';
});
这将只检查两个字段不能同时为空,并且当另一个字段为空时,一个字段是必需的

但是,这将为用户留下两个选项


如果您想验证两者不能都为空,但同时只能设置1(xor),则必须扩展验证器,因为这在Laravel中不存在

将其放入AppServiceProvider的
boot()
方法:

Validator::extendImplicit('xor', function ($attribute, $value, $parameters, $validator) {
    return empty($value) || empty(data_get($validator->getData(), $parameters[0]));
});
然后您可以使用:

$v->sometimes('single_item_make', 'required_without:single_item_make_other|xor:single_item_make_other', function ($input) {
    return $input->policy_type === 'single';
});

$v->sometimes('single_item_make_other', 'required_without:single_item_make|xor:single_item_make', function ($input) {
    return $input->policy_type === 'single';
});
在这种情况下,
required\u不带
确保如果1为空,则需要另一个1,
xor
验证确保如果设置了1,则另一个1不能有值

您可以在验证中添加自定义错误消息,也可以使用自定义验证程序并将这些验证消息传递到那里

更多信息:


我没有测试这两段代码,但它们应该可以工作。

您尝试过使用“nullable”吗?我们不希望它们可以为nullable。我们需要将它们验证为已填充,而不是空/空。该字段被插入到不能将Null作为值的数据库中。请尝试使用“required_if”而不是“required_if”。检查此线程以了解更多信息:文档说
required\u如果:另一个字段,值,。。。如果另一个字段等于任何值,则验证中的字段必须存在且不为空。
因此,此处不适用此字段。您的验证表明两者都需要存在。将每个语句中的第二个if替换为a而不使用,并且它仍将尝试验证另一个if。('single_item_make_other'=>'required_if:policy_type,single | required_not:single_item_make')我们尝试了这一方法(在问题注释中指出),但失败了。它仍然试图验证另一个字段。@MikeRampling您能显示您的刀片吗?我能更好地理解你的背景。