【问题标题】:How to bypass muliple validation attribute values inside validation messages in Laravel?如何绕过 Laravel 验证消息中的多个验证属性值?
【发布时间】:2018-04-14 09:25:33
【问题描述】:

我制作了一个自定义验证器,它比较两个日期,我想向用户显示一条消息,说明一个日期(在我的示例中为 invoicedate)必须早于另一个日期(@ 987654323@ 在我的例子中)。

在我的自定义验证器中,我编写:

public static validateInfo(Request $request)
{
    $validator = Validator::make($request->all(), [
        'referencenumber' => 'required|min:2|max:64',
        'invoicedate' => 'required|date',
        'deadline' => 'null|date'
    ]);
    $validator->after(function ($validator) use ($request) { // custom static function where I compare two dates using strtotime(), if invoicedate and deadline are still valid, and return false or true
        if (InvoiceValidator::invalidDeadline($validator, $request)) {
            $validator->errors()->add('deadline', __('validation.negative_date_difference', [
                'attribute1' => 'deadline',
                'attribute2' => 'invoicedate'
            ]));
        }
    });
    return $validator;
}

resources\lang\en\validation.php里面我写:

<?php
return [
    // ...
    'negative_date_difference'  => 'The :attribute1 may not be earlier than the :attribute2.',
    // ...
    'attributes' => [
        'referencenumber' => 'Reference Number', // This works. It's fine
        'invoicedate' => 'Invoice Date' // But this does not work, of course, because I wrote $validator->errors()->add('deadline'...); so the deadline is the only targetted attribute name here
    ],
]

当前输出为:

截止日期不得早于发票日期。


我的问题:如何绕过invoicedate,当这是我想看到的消息?

截止日期不得早于发票日期。

【问题讨论】:

  • before 还没有这样做吗?
  • 我不知道。什么意思?
  • 类似$rules = [ "invoicedate" =&gt; "before:".$request-&gt;deadline ] 的东西会以invoiceDate must be before &lt;the date&gt; 失败。自定义消息的占位符将是发票日期的:attribute 和其他日期的:date
  • 啊好吧...我会试试的。谢谢!我找到了 1 个可行的解决方案(目前),但我也会尝试您的解决方案。

标签: php laravel multilingual customvalidator laravel-validation


【解决方案1】:

resources\lang\en\messages.php里面我添加了一条新消息:

<?php
return [
    'invoice_date' => 'Invoice Date'
]

然后编辑我的自定义验证函数,如下:

if (InvoiceValidator::invalidDeadline($validator, $request)) {
    $validator->errors()->add('deadline', __('validation.negative_date_difference', [
        'attribute1' => 'deadline',
        'attribute2' => __('messages.invoice_date') // This works
    ]));
}

【讨论】:

    猜你喜欢
    • 2016-01-09
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 2023-03-08
    • 2018-12-17
    • 2017-02-09
    • 1970-01-01
    • 2021-02-08
    相关资源
    最近更新 更多