You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8.75自定义验证规则无法返回指定消息,如何解决?

Laravel自定义验证规则未返回指定错误消息的解决方法

问题场景

使用Laravel 8.75开发时,自定义了货币格式验证规则FlexibalCurrencyRule,但验证失败时,返回的错误信息显示规则类名而非message()方法中定义的"currency"字符串。

自定义规则代码

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class FlexibalCurrencyRule implements Rule
{
    private $regex = '/^([0-9]{1,10})([\.,][0-9]{1,2})?$/';

    public function __construct()
    {
        //
    }

    public function passes($attribute, $value)
    {
        return preg_match($this->regex, $value);
    }

    public function message()
    {
        return "currency";
    }
}

控制器调用代码

$requestDto = json_decode($request->getContent(), true);

$validator = Validator::make($requestDto, [
    'name' => 'required|max:100',
    'price' => ['required', new FlexibalCurrencyRule],
]);

if ($validator->fails()) {
    // 返回响应
}

错误返回示例

"price": {
    "App\\Rules\\FlexibalCurrencyRule": []
}

解决办法

1. 修正message()方法返回值

Laravel允许message()返回字符串或数组,但返回纯"currency"可能被识别为翻译键(若语言文件中无对应条目,会导致规则类名被展示)。建议返回包含字段占位符的完整提示:

public function message()
{
    return "The :attribute must be a valid currency format.";
}

若仍需使用"currency"作为消息,确保语言文件(如resources/lang/en/validation.php)中存在对应条目:

// 在validation.php的custom数组中添加
'custom' => [
    'price' => [
        'flexibal-currency-rule' => 'currency',
    ],
],

2. 手动指定规则错误消息

创建Validator时,通过第三个参数直接为自定义规则绑定错误消息:

$validator = Validator::make($requestDto, [
    'name' => 'required|max:100',
    'price' => ['required', new FlexibalCurrencyRule],
], [
    'price.App\Rules\FlexibalCurrencyRule' => 'currency',
]);

3. 调整错误响应的返回逻辑

确保返回响应时正确提取错误文本,而非直接返回错误对象的原始结构。例如:

if ($validator->fails()) {
    return response()->json([
        'errors' => $validator->errors()->messages()
    ], 422);
}

或者将所有错误消息整理为数组返回:

if ($validator->fails()) {
    return response()->json([
        'errors' => $validator->errors()->all()
    ], 422);
}

内容的提问来源于stack exchange,提问作者Martijn Hiemstra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 22:24:53