php - Laravel 中的自定义验证消息

标签 php laravel laravel-5

我需要一条错误消息,基本上是“您需要在至少一个多下拉列表中选中至少一个框”

我的五个多下拉名称是; Country、County、Gor、Locauth、Parlc。

到目前为止我的 Controller 是;

$rules = Array
(
  [country] => required_without_all:county,gor,locauth,parlc
  [county] => required_without_all:country,gor,locauth,parlc
  [gor] => required_without_all:country,county,locauth,parlc
  [locauth] => required_without_all:country,county,gor,parlc
  [parlc] => required_without_all:country,county,gor,locauth
)

$validator = \Validator::make($input, $rules);

我的问题是我看不到只返回一条规则的方法。它返回 5 个非常相似的措辞规则;

The country field is required when none of county / gor / locauth / parlc are present.
The county field is required when none of country / gor / locauth / parlc are present.
The gor field is required when none of country / county / locauth / parlc are present.
The locauth field is required when none of country / county / gor / parlc are present.
The parlc field is required when none of country / county / gor / locauth are present.

不精彩!有没有办法只返回一条自定义消息?

--- 编辑 ---

我应该补充... 上面的 Array() 代码不是实际代码,它是创建这些规则的实际代码的 print_r 结果。我只是认为这会让我的问题更容易阅读和理解。实际的代码,如果你感兴趣的话是这个;

$fields = ['country','county','gor','locauth','parlc'];
    $rules = [];
    foreach ($fields as $i => $field) {
        $rules[$field] = 'required_without_all:' . implode(',', array_except($fields, $i));
    }

--- 另一个编辑 ---

我已经知道自定义错误消息,例如;

$messages = [
'required' => 'The :attribute field is required.',
];

$validator = Validator::make($input, $rules, $messages);

但这只会给我五个错误消息,而不是一个。

最佳答案

您只需要一个字段上的规则就可以正常工作。最简单的方法是创建一个空字段并将规则应用于它。该字段不必存在于数据库架构中或应用程序中的任何其他位置。

public static $rules = [
    location => required_without_all:country,county,gor,locauth,parlc
];

然后在您的语言文件中自定义消息。

'custom' => array(
    'location' => array(
        'required_without_all' => 'At least one location field is required',
    ),
),

现在,当所有字段(或您案例中的复选框)为空时,您将收到错误消息。填写一项或多项,不会有任何错误。

关于php - Laravel 中的自定义验证消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29828017/

相关文章:

php - 具有自定义枢轴模型的 Laravel 5.2 三向枢轴

php - 在 JavaScript 中解密 PHP AES/CBC 加密字符串

php - 预加载图像以防止可见图像加载的最可靠方法? (没有JS)

php - 对于从 C++ 开始的 php 开发人员,是否有一个地方可以让我们看到 PHP <=> C++ 等效库/函数?

css - 使用 vuejs 和 laravel 消除导航栏和旋转木马之间的差距

Laravel 5.2 和收银员

php - 如何在 PHP 中使用正则表达式修复 PATHS 的路径而不破坏 URL?

php - 到 Controller 的 laravel 路由被调用两次

php - Laravel WHERE 查询单列结果

Laravel 5.0 文件夹结构 : public vs. 资源