php - 带有 "sometimes"规则的 Laravel Validator 自定义消息

这是我的一段代码,用于验证表单输入:

public function saveData(Request $request){
    $form_data = $request->all();

    $validation_fields = [
        'first_name' => 'required',
        'last_name' => 'required',
        'cod_fisc' => 'sometimes|required|size:16',
        'p_iva' => 'sometimes|required|between:11,13'
    ];

    $errorMsgs = [
        'first_name.required' => 'Il campo Nome è obbligatorio.',
        'last_name.required' => 'Il campo Cognome/Ragione sociale è obbligatorio.',
        'cod_fisc.required' => 'Il campo Codice Fiscale deve contenere 16 caratteri',
        'p_iva.required' => 'Il campo Partita Iva deve contenere 11 o 13 caratteri',
    ];

    $validator = Validator::make($form_data, $validation_fields, $errorMsgs);

    ....
}

整个项目是为意大利人编写的,因此所有消息都必须使用意大利语。 一切正常,但绑定(bind)到“有时”规则的 cod_fiscp_iva 的两个规则以英文显示。我的自定义错误消息被忽略。

为什么?

最佳答案

在搜索您的问题时,我找到了这个链接:https://laracasts.com/discuss/channels/laravel/sometimes-validator-with-custom-message

其中包含类似的问题。初始代码是

$v = Validator::make(
                    $request->all(),
                    [ 'first_name' => 'required|max:60'],
                    ['first_name.required' => 'First name is really required, yo']
);

$v->sometimes('last_name', 'required|in:fake', function($input){
                    return true;
});

解决方案是

$v = Validator::make(
                    $request->all(),
                    [ 'first_name' => 'required|max:60'],
                    ['first_name.required' => 'First name is really required, yo'],
                    ['last_name.in' => 'Last name must be fake, too']
);

$v->sometimes('last_name', 'required|in:fake', function($input){
                    return true;
});

显然,您可能会在 Validator::make 的结果上调用有时 function 并传递字段名称、验证器签名和一个 bool 函数

关于php - 带有 "sometimes"规则的 Laravel Validator 自定义消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63574514/

相关文章:

Python - 在 asyncio 中取消任务?

amazon-web-services - AWS API 网关上的剥离 header

java - 无法在数据库中使用 BCryptPassword 保存加密密码

ruby-on-rails - 在 Rails 中进行 View 更新的正确方法

python - 如何启用对 Dash DataTable 上特定行的编辑

git - 以编程方式为新的 Azure 存储库设置默认分支名称

python-3.x - Python3 Beautifulsoup4 从多个容器兄弟中提取文本

c# - 如何从 .NET Core 3.1 中的 DI 获取 SignalR IHubContex

javascript - 在 quill-image-resize-vue 中对齐时出错

python - 从数据框创建字典,其中多列的元组作为键,另一列作为值