没有不值得去解决的问题,也没有不值得去学习的技术!

Customizing Attribute Names in Chinese for Laravel 5.4 Form Validation Errors

Laravel's form validation error messages contain English text, primarily the validated attribute name: winning limit

1. In Laravel’s form validation, the error messages contain English text, primarily the validated attribute name: winning limit. See Figure 1.

Laravel's form validation error messages contain English text, primarily the validated attribute name: winning limit
Figure 1
JSON

{
  "code": 10000,
  "message": "winning limit 必须是整数。",
  "data": []
}

2. The validation code is as follows:

PHP

        $input = $request->json()->all();
        Arr::set($input, 'activity_id', $activityId);
        $factory = Container::getInstance()->make('validator');
        $validator = $factory->make($input, [
            'activity_id' => 'required|uuid|exists:activities,id',
            'prize_id' => 'required|uuid|exists:prizes,id',
            'winning_limit' => 'integer',
            'stock_limit' => 'numeric',
            'winning_probability' => 'numeric|between:0,1',
        ]);

3. Reference URL: https://learnku.com/docs/laravel/5.4/validation/1234#42c1ed . Customizing attributes in the language file. If you want to replace the :attribute portion of the validation message with a custom attribute name, you can specify the custom name in the attributes array of the resources/lang/xx/validation.php language file. Edit: resources/lang/zh-CN/validation.php

PHP

    'attributes'           => [
		'winning_limit'         => '中奖限制',
    ],

4. In Laravel’s form validation, the attribute name in the error message: winning limit has been replaced with: 中奖限制. This matches expectations. See Figure 2.

In Laravel's form validation, the attribute name in the error message: winning limit has been replaced with: 中奖限制. This matches expectations.
Figure 2
JSON

{
  "code": 10000,
  "message": "中奖限制 必须是整数。",
  "data": []
}

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系