数组元素的自定义 laravel 验证器?

Custom laravel validator for array element?

我想自定义我的 laravel 验证器。

截至目前我有多个复选框

<input type="checkbox" name="prodRelatedID[]" value="1">
<input type="checkbox" name="prodRelatedID[]" value="5">
<input type="checkbox" name="prodRelatedID[]" value="189">

在我的 Request.php 文件中有这个

public function rules()
{
    return [
        'prodTitle' => ['required', 'string', 'max:255'],
        'prodDesc' => ['required', 'string', 'max:255'],
        'attachment' => ['image','mimes:jpeg,png,jpg,gif,svg','max:2048'],
        'prodSize' => ['required','string','max:255'],
        'prodCategory' => ['required','string','max:255'],
        'prodPrice' =>  ['required','regex:/^\d*(\.\d{1,2})?$/'],
        'prodRelatedID' => ['required'],
        'prodRelatedID.*' => ['accepted'],
    ];
}

现在如何自定义错误消息,就像 prodRelatedID 一样?

如果用户没有选中复选框,这将return像这样

Please choose atleast 1 product related

如果您使用的是表单请求,那么您只需覆盖消息方法即可:

public function messages()
{
    return [
        'prodRelatedID.required' => 'Please choose at least 1 product related',
    ];
}

有两种方法可以做到这一点:

1 添加消息数组以匹配您的规则,并将其发送到验证方法

$messages = [
    'prodRelatedId.required' => 'Please choose at least 1 product related'
]

$request->validate($rules, $messages);

或者 2,我更喜欢的更简洁的方法是编辑

resources\assets\lang\en\validation.php

并修改文件末尾的 "attributes" 键并在其中添加您的值:

'attributes' => [
    'prodRelatedID' => 'product related'
]