php - 拉拉维尔 7 : array validation messages with wildcard index

标签 php laravel validation laravel-7

所以我有一个数据数组(不一定来自 $request)

       $validator = Validator::make($array, [
           '*.client_name' => 'required',
           '*.client_phone' => ['required ', 'regex:/^(0)(5|6|7)[0-9]{8}/'],
       ]);

       $validator->validate();

到目前为止,验证消息显示为

The field 1.client_name is required

我想要类似的东西

Row 1 : The field client_name is required

如果我使用 $validator->setAttributeNames($newAttributeNames); 即使我在新属性名称中设置了通配符,我也会丢失通配符 (*) 中的行号。

另请注意,我不想覆盖 laravel 提供的所有规则的消息(这里有 2 个示例,但实际上我有很多规则)

那么知道如何实现这一点吗?

最佳答案

到目前为止我能找到的最好方法是受到@Tim Welis 答案的启发,但使用循环

$rules = [
    '*.client_name' => 'required',
    '*.client_phone' => ['required ', 'regex:/^(0)(5|6|7)[0-9]{8}/'],
    '*.age' => 'required | numeric | between:0,100',
];

$messages = [];
foreach($array as $rowNum => $row)
{
    foreach($row as $field => $value) {
        $messages["{$rowNum}.".$field.'.required'] = "Row {$rowNum} : The field {$field} is required";
        $messages["{$rowNum}.".$field.'.regex'] = "Row {$rowNum} : The field {$field} format is invalid";
        $messages["{$rowNum}.".$field.'.numeric'] = "Row {$rowNum} : The field {$field} must be numeric";
        $messages["{$rowNum}.".$field.'.between'] = "Row {$rowNum} : The field {$field} value must be between :min - :max";
    }
}

$validator = Validator::make($array, $rules, $messages);
$validator->validate();   

对于所有属性,规则消息仅写入一次

关于php - 拉拉维尔 7 : array validation messages with wildcard index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64121865/

相关文章:

php - 我无法访问 http ://localhost/phpmyadmin/

php - 对自定义类的依赖注入(inject)陷入 L4.2 中的无限循环?

php - 使用 Eloquent 更新数组列表中的多个 id

java - 在 Java 中使用多个 XSD 验证 XML

JavaScript - 如果电子邮件错误则设置类

php - 为什么 date_create_from_format 总是为我返回 false?

javascript - 使用提交按钮保存响应 (html)

php - 移动到新服务器后无法写入 MYSQL DB

php - 一般错误 : 1364 Field 'identifier' doesn't have a default value

javascript - 在 React Router v4 中验证 URL 参数