【问题标题】:How to get only the array key with laravel validation message?如何仅获取带有 laravel 验证消息的数组键?
【发布时间】:2020-01-28 18:59:09
【问题描述】:

我有一个待验证的数组。验证工作正常。但我无法返回正确的消息。

我的请求数组是这样的

mobile = 'tom'=> '0011120', 'dick'=> null, 'harry'=>'001212'

如您所见,dick 的手机号码为空。它应该返回一个错误。 'the mobile number of dick is required.'

我试过了,

$validator = Validator::make(request()->all(),
[
    'mobile.*' => 'required'
],
[
    'mobile.*.required' => 'the mobile number of :key is required.'
];

当我返回错误类似于'the mobile number of mobile.dick is required.' 如何删除mobile.dick 并仅获取名称部分?

【问题讨论】:

  • 你试过'mobile.*.required' =>' :attribute 的手机号码是必需的。' ?
  • 你想忽略只有 dick 名字的验证规则吗?
  • @Qonvex620 是的......同样的消息即将到来
  • @BKF.. 我不想忽略任何规则。规则部分运行良好。消息部分出现问题。

标签: php laravel validation


【解决方案1】:

我认为这是不可能的,因为他们在 :key 和 messageKey 上使用了简单的 str_replace

你可以稍微覆盖它,使用你自己的变量,这不是很棒的代码,但会起作用:

$validator = Validator::make(request()->all(),
[
    'mobile.*' => 'required'
],
[
    'mobile.*.required' =>'the mobile number of :key is required.'
];

$errors = null;
if ($validator->errors()) {
    $errors = [];
    foreach ($validator->errors()->all() as $error) {
        $errors []= str_replace('mobile.', '', $error);
    }
}

// $errors will contain proprer message, or null if no error
dd($errors);

【讨论】:

  • 是的!你是对的,因为我在我的电脑上记录了它来测试它,他可以替换整个消息。
  • 它正在工作。我刚刚添加了一个 $errors = new MessageBag($errors);以便它返回一个消息包;不是数组。
【解决方案2】:

试试这样的:

 'mobile.*.required' =>'the mobile number of '.str_replace('mobile.','',:key) .'is required.'

【讨论】:

  • 它给了我错误。 “语法错误,意外':'”.. str_replace('mobile.','',:key),,,这里:key可能不可接受。
猜你喜欢
  • 2018-03-11
  • 2020-02-13
  • 1970-01-01
  • 2020-06-20
  • 1970-01-01
  • 2016-10-25
  • 2019-04-15
  • 2016-05-27
  • 2015-10-25
相关资源
最近更新 更多