验证检查字段不为空

问题描述 投票:0回答:2

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

对于上下文来说,它是一个设备的品牌,我们有一个品牌/品牌清单,但如果你的设备没有显示,可以选择手动编写。但是我们需要验证手动输入字段是否为空,但仅限于它们已跳过第一个列表。

'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,'

我们尝试了上述内容并且无法正常工作,我们似乎无法在文档中找到有关检查字段为空的内容。

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

laravel laravel-5.3
2个回答
1
投票

在这种情况下,你不能将required_ifrequired_without结合起来,因为它会发生冲突。

在您当前的代码中,两者的第一条规则是:

required_if:policy_type,single

如果policy_type === '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_without确保如果1为空,则另一个是必需的,并且xor验证确保如果设置为1,则另一个1不能具有值。

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

更多信息:https://laravel.com/docs/5.7/validation#conditionally-adding-rules

我没有测试过这两段代码,但它们应该可以运行。


0
投票

正如required_without文档所示,您需要使用如下:

'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,'
© www.soinside.com 2019 - 2024. All rights reserved.