【问题标题】:Laravel Validation Rules - require the field to be explicitly empty contingent on the value of another field (type_id)Laravel 验证规则 - 要求字段显式为空,具体取决于另一个字段的值 (type_id)
【发布时间】:2022-01-14 05:35:12
【问题描述】:

问题

我正在处理发票行。当行类型为“纯文本”时,价格和数量字段应为空白。

当行类型为“项目”时,价格和数量字段是必需的。

Laravel 已经做了什么:

required_if 函数非常适合说“好的,这是一个项目行,需要数量和价格。

我需要什么:

一个功能类似,但希望该字段为空,防止用户将价格和数量与纯文本行相对。

我是如何使用规则的:

class StoreInvoiceRequestDetail extends FormRequest
{
   public function rules()
    {
        return [
            'type_id'               => 'required|integer|exists:invoice_request_detail_types,id',
            'item_price'            => [
                'nullable',
                'numeric',
                'empty_if:type_id,'.InvoiceRequestDetailType::TEXT_ONLY.',Line Type,Text Only',
                'required_if:type_id,'.InvoiceRequestDetailType::ITEM.'Line Type,Item',
            ],
            'item_quantity'         => [
                'nullable',
                'numeric',
                'empty_if:type_id,'.InvoiceRequestDetailType::TEXT_ONLY.',Line Type,Text Only',
                'required_if:type_id,'.InvoiceRequestDetailType::ITEM.',Line Type,Item',
            ],
            'description'           => 'required|string|min:3|max:'.ApplicationConstant::STRING_LONG,
            'invoice_request_id'    => 'required|integer|exists:invoice_requests,id',
        ];
    }
}

【问题讨论】:

    标签: php laravel validation required-field


    【解决方案1】:

    这行得通:

    用法

        'item_price' => 'empty_if:type_id,1,Line Type,Text Only',
    

    扩展器

            Validator::extend('empty_if', function ($attribute, $value, $parameters, $validator)
            {
                $other = $parameters[0];
                $otherValue = $parameters[1];
                return !(Input::get($other) == $otherValue &&! empty($attribute));
            });
    
            Validator::replacer('empty_if', function ($message, $attribute, $rule, $parameters) {
                $other = isset($parameters[2]) ? $parameters[2] : $parameters[0];
                $value = isset($parameters[3]) ? $parameters[3] : $parameters[1];
                return str_replace([':other', ':value'], [ $other, $value ], $message);
            });
    

    验证器语言

     'empty_if'             => 'The :attribute must be empty when :other is ":value"',
    

    为了便于使用,我在替换器中添加了字段名称和值别名选项,但从技术上讲,我可能应该只调用我的字段 invoice_request_line_type_id 而不是 type_id。在这种情况下,值 lang 并不能真正为我工作,这是一个陷阱,因为它不会被翻译,但无论如何您都可以将这些值从 Lang 插入到验证器中。

    【讨论】:

      猜你喜欢
      • 2017-06-07
      • 2019-02-05
      • 1970-01-01
      • 2021-04-20
      • 1970-01-01
      • 2017-08-26
      • 2020-10-23
      • 2019-03-18
      • 2022-01-17
      相关资源
      最近更新 更多