Laravel多语言验证信息怎么配

wen PHP项目 2

本文目录导读:

Laravel多语言验证信息怎么配

  1. 基础语言文件配置
  2. 配置语言环境
  3. 创建自定义属性名称(推荐做法)
  4. 在控制器中使用
  5. 自定义验证消息
  6. 动态切换语言
  7. 中间件实现语言切换
  8. 最佳实践建议
  9. 前端显示错误信息
  10. 完整示例

在 Laravel 中配置多语言验证信息,主要通过语言文件验证器的配合实现,以下是完整的配置步骤和最佳实践:

基础语言文件配置

创建语言文件

# 为中文创建验证语言文件
php artisan lang:publish zh_CN

或者手动创建:

resources/lang/
├── en/
│   └── validation.php
└── zh_CN/
    └── validation.php

中文验证语言文件示例 (resources/lang/zh_CN/validation.php)

<?php
return [
    /*
    |--------------------------------------------------------------------------
    | 验证语言行
    |--------------------------------------------------------------------------
    |
    | 以下语言行包含验证器使用的默认错误消息。
    | 您可以随意修改这些消息。
    |
    */
    'accepted'             => ':attribute 必须接受。',
    'active_url'           => ':attribute 不是一个有效的网址。',
    'after'                => ':attribute 必须是一个在 :date 之后的日期。',
    'after_or_equal'       => ':attribute 必须是一个在 :date 之后的日期(包括当天)。',
    'alpha'                => ':attribute 只能由字母组成。',
    'alpha_dash'           => ':attribute 只能由字母、数字、短划线和下划线组成。',
    'alpha_num'            => ':attribute 只能由字母和数字组成。',
    'array'                => ':attribute 必须是一个数组。',
    'before'               => ':attribute 必须是一个在 :date 之前的日期。',
    'before_or_equal'      => ':attribute 必须是一个在 :date 之前的日期(包括当天)。',
    'between'              => [
        'numeric' => ':attribute 必须在 :min 和 :max 之间。',
        'file'    => ':attribute 必须在 :min 和 :max KB 之间。',
        'string'  => ':attribute 必须在 :min 和 :max 个字符之间。',
        'array'   => ':attribute 必须在 :min 和 :max 项之间。',
    ],
    'boolean'              => ':attribute 字段必须为 true 或 false。',
    'confirmed'            => ':attribute 确认不匹配。',
    'date'                 => ':attribute 不是一个有效的日期。',
    'date_equals'          => ':attribute 必须等于 :date。',
    'date_format'          => ':attribute 与格式 :format 不匹配。',
    'different'            => ':attribute 和 :other 必须不同。',
    'digits'               => ':attribute 必须是 :digits 位数字。',
    'digits_between'       => ':attribute 必须在 :min 和 :max 位数字之间。',
    'dimensions'           => ':attribute 图片尺寸无效。',
    'distinct'             => ':attribute 字段有重复值。',
    'email'                => ':attribute 必须是一个有效的邮箱地址。',
    'exists'               => '选中的 :attribute 无效。',
    'file'                 => ':attribute 必须是一个文件。',
    'filled'               => ':attribute 字段不能为空。',
    'gt'                   => [
        'numeric' => ':attribute 必须大于 :value。',
        'file'    => ':attribute 必须大于 :value KB。',
        'string'  => ':attribute 必须大于 :value 个字符。',
        'array'   => ':attribute 必须大于 :value 项。',
    ],
    'gte'                  => [
        'numeric' => ':attribute 必须大于或等于 :value。',
        'file'    => ':attribute 必须大于或等于 :value KB。',
        'string'  => ':attribute 必须大于或等于 :value 个字符。',
        'array'   => ':attribute 必须大于或等于 :value 项。',
    ],
    'image'                => ':attribute 必须是一个图片。',
    'in'                   => '选中的 :attribute 无效。',
    'in_array'             => ':attribute 不在 :other 中。',
    'integer'              => ':attribute 必须是一个整数。',
    'ip'                   => ':attribute 必须是一个有效的 IP 地址。',
    'ipv4'                 => ':attribute 必须是一个有效的 IPv4 地址。',
    'ipv6'                 => ':attribute 必须是一个有效的 IPv6 地址。',
    'json'                 => ':attribute 必须是一个有效的 JSON 字符串。',
    'lt'                   => [
        'numeric' => ':attribute 必须小于 :value。',
        'file'    => ':attribute 必须小于 :value KB。',
        'string'  => ':attribute 必须小于 :value 个字符。',
        'array'   => ':attribute 必须小于 :value 项。',
    ],
    'lte'                  => [
        'numeric' => ':attribute 必须小于或等于 :value。',
        'file'    => ':attribute 必须小于或等于 :value KB。',
        'string'  => ':attribute 必须小于或等于 :value 个字符。',
        'array'   => ':attribute 必须小于或等于 :value 项。',
    ],
    'max'                  => [
        'numeric' => ':attribute 不能大于 :max。',
        'file'    => ':attribute 不能大于 :max KB。',
        'string'  => ':attribute 不能大于 :max 个字符。',
        'array'   => ':attribute 不能大于 :max 项。',
    ],
    'mimes'                => ':attribute 必须是 :values 格式的文件。',
    'mimetypes'            => ':attribute 必须是 :values 格式的文件。',
    'min'                  => [
        'numeric' => ':attribute 必须至少为 :min。',
        'file'    => ':attribute 必须至少为 :min KB。',
        'string'  => ':attribute 必须至少为 :min 个字符。',
        'array'   => ':attribute 必须至少为 :min 项。',
    ],
    'multiple_of'          => ':attribute 必须是 :value 的倍数。',
    'not_in'               => '选中的 :attribute 无效。',
    'not_regex'            => ':attribute 格式无效。',
    'numeric'              => ':attribute 必须是一个数字。',
    'password'             => '密码错误。',
    'present'              => ':attribute 字段必须存在。',
    'regex'                => ':attribute 格式无效。',
    'required'             => ':attribute 字段是必需的。',
    'required_if'          => '当 :other 为 :value 时,:attribute 字段是必需的。',
    'required_unless'      => '当 :other 不为 :values 时,:attribute 字段是必需的。',
    'required_with'        => '当 :values 存在时,:attribute 字段是必需的。',
    'required_with_all'    => '当 :values 都存在时,:attribute 字段是必需的。',
    'required_without'     => '当 :values 不存在时,:attribute 字段是必需的。',
    'required_without_all' => '当 :values 都不存在时,:attribute 字段是必需的。',
    'same'                 => ':attribute 和 :other 必须匹配。',
    'size'                 => [
        'numeric' => ':attribute 必须是 :size。',
        'file'    => ':attribute 必须是 :size KB。',
        'string'  => ':attribute 必须是 :size 个字符。',
        'array'   => ':attribute 必须包含 :size 项。',
    ],
    'starts_with'          => ':attribute 必须以 :values 开头。',
    'string'               => ':attribute 必须是一个字符串。',
    'timezone'             => ':attribute 必须是一个有效的时区。',
    'unique'               => ':attribute 已经被占用。',
    'uploaded'             => ':attribute 上传失败。',
    'url'                  => ':attribute 格式无效。',
    'uuid'                 => ':attribute 必须是有效的 UUID。',
    /*
    |--------------------------------------------------------------------------
    | 自定义验证属性名称
    |--------------------------------------------------------------------------
    |
    | 以下行用于将属性名称替换为更友好的名称,
    | 如 "email" 替换为 "邮箱地址"。
    |
    */
    'attributes' => [
        'email' => '邮箱地址',
        'password' => '密码',
        'name' => '姓名',
        'phone' => '手机号码',
        'age' => '年龄',
    ],
];

配置语言环境

config/app.php 中设置默认语言:

'locale' => 'zh_CN', // 默认使用中文
'fallback_locale' => 'en', // 回退语言
'available_locales' => [
    'en',
    'zh_CN',
    'ja', // 添加其他语言
],

创建自定义属性名称(推荐做法)

创建独立的属性语言文件

resources/lang/zh_CN/attributes.php:

<?php
return [
    'email' => '邮箱地址',
    'password' => '密码',
    'name' => '姓名',
    'phone' => '手机号码',
    'age' => '年龄',
    'gender' => '性别',
    'address' => '地址',
    'city' => '城市',
    'country' => '国家',
    'postal_code' => '邮政编码', => '标题',
    'content' => '内容',
    'description' => '描述',
    'category' => '分类',
    'price' => '价格',
    'quantity' => '数量',
    'status' => '状态',
];

在控制器中使用

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class UserController extends Controller
{
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:8|confirmed',
            'age' => 'required|integer|min:18|max:120',
            'phone' => 'required|regex:/^1[3-9]\d{9}$/',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'errors' => $validator->errors()
            ], 422);
        }
        // 处理保存...
    }
}

自定义验证消息

在请求类中自定义:

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CreateUserRequest extends FormRequest
{
    public function rules()
    {
        return [
            'email' => 'required|email|unique:users',
            'password' => 'required|min:8',
            'age' => 'required|integer|min:18',
        ];
    }
    public function messages()
    {
        return [
            'email.required' => '请输入邮箱地址',
            'email.email' => '请输入有效的邮箱格式',
            'email.unique' => '该邮箱已被注册',
            'password.required' => '请输入密码',
            'password.min' => '密码至少需要8个字符',
            'age.required' => '请输入年龄',
            'age.min' => '年龄必须大于或等于18岁',
        ];
    }
    public function attributes()
    {
        return [
            'email' => '邮箱地址',
            'password' => '密码',
        ];
    }
}

动态切换语言

在控制器中切换:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class LocaleController extends Controller
{
    public function switchLang($locale)
    {
        if (in_array($locale, ['en', 'zh_CN', 'ja'])) {
            app()->setLocale($locale);
            session()->put('locale', $locale);
        }
        return redirect()->back();
    }
}

中间件实现语言切换

<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\App;
class SetLocale
{
    public function handle($request, Closure $next)
    {
        if (session()->has('locale')) {
            App::setLocale(session()->get('locale'));
        }
        return $next($request);
    }
}

最佳实践建议

使用属性文件分离

// 在验证消息中使用 :attribute 占位符
'required' => ':attribute 是必需的',
// 在 attributes.php 中定义友好名称
'email' => '邮箱地址',

创建自定义验证规则

// App\Rules\ChinesePhone.php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class ChinesePhone implements Rule
{
    public function passes($attribute, $value)
    {
        return preg_match('/^1[3-9]\d{9}$/', $value);
    }
    public function message()
    {
        return ':attribute 格式不正确,请输入有效的手机号码';
    }
}

使用验证器定制

Validator::extend('chinese_phone', function ($attribute, $value, $parameters, $validator) {
    return preg_match('/^1[3-9]\d{9}$/', $value);
});
// 添加验证消息
Validator::replacer('chinese_phone', function ($message, $attribute, $rule, $parameters) {
    return str_replace(':attribute', $attribute, ':attribute 必须是有效的中国手机号码');
});

前端显示错误信息

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
<!-- 针对单个字段 -->
<input type="text" name="email" class="@error('email') is-invalid @enderror">
@error('email')
    <div class="invalid-feedback">{{ $message }}</div>
@enderror

完整示例

// 创建一个完整的验证请求
php artisan make:request StoreUserRequest
// StoreUserRequest.php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreUserRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }
    public function rules()
    {
        return [
            'name' => 'required|string|max:50',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|string|min:8|confirmed',
            'phone' => ['required', new \App\Rules\ChinesePhone],
            'age' => 'required|integer|min:18|max:120',
        ];
    }
    public function messages()
    {
        return [
            'name.required' => '请输入用户名',
            'email.required' => '邮箱地址不能为空',
            'email.unique' => '该邮箱已被注册',
            'password.confirmed' => '两次输入的密码不一致',
            'age.min' => '年龄必须年满18岁',
        ];
    }
    public function attributes()
    {
        return [
            'name' => '用户名',
            'email' => '邮箱地址',
            'password' => '密码',
            'phone' => '手机号码',
            'age' => '年龄',
        ];
    }
}

这样配置后,Laravel 会根据当前语言环境自动使用对应的验证信息,并且可以针对不同的业务场景自定义错误消息。

抱歉,评论功能暂时关闭!