Laravel 表单验证:自定义错误信息 1 个改进

如果有需要的话,你也可以使用自定义错误消息取代默认值进行验证。有几种方法可以指定自定义消息。首先,你可以将自定义消息作为第三个参数传递给 Validator::make 方法:

$messages = [
    'required' => 'The :attribute field is required.',
];

$validator = Validator::make($input, $rules, $messages);

在这个例子中,:attribute 占位符会被验证字段的实际名称取代。除此之外,你还可以在验证消息中使用其它占位符。例如:

$messages = [
    'same'    => 'The :attribute and :other must match.',
    'size'    => 'The :attribute must be exactly :size.',
    'between' => 'The :attribute value :input is not between :min - :max.',
    'in'      => 'The :attribute must be one of the following types: :values',
];

为给定属性指定自定义消息

有时候你可能只想为特定的字段自定义错误消息。只需在属性名称后使用「点」语法来指定验证的规则即可:

$messages = [
    'email.required' => 'We need to know your e-mail address!',
];

在语言文件中指定自定义消息

在大多数情况下,您可能会在语言文件中指定自定义消息,而不是直接将它们传递给 Validator。为此,需要把你的消息放置于 resources/lang/xx/validation.php 语言文件内的 custom 数组中。

'custom' => [
    'email' => [
        'required' => 'We need to know your e-mail address!',
    ],
],

在语言文件中指定自定义属性

如果你希望将验证消息的 :attribute 占位符替换为自定义属性名称,你可以在 resources/lang/xx/validation.php 语言文件的 attributes 数组中指定自定义名称:

'attributes' => [
    'email' => 'email address',
],

在语言文件中指定自定义值

有时可能需要将验证消息的 :value 占位符替换为值的自定义文字。例如,如果 payment_type 的值为 cc,使用以下验证规则,该规则指定需要信用卡号:

$request->validate([
    'credit_card_number' => 'required_if:payment_type,cc'
]);

如果此验证规则失败,则会产生以下错误消息:

    当payment type为cc时,credit card number 不能为空。

您可以通过定义 values 数组,在 validation 语言文件中指定自定义值表示,而不是显示 cc 作为支付类型值:

'values' => [
    'payment_type' => [
        'cc' => '信用卡'
    ],
],

现在,如果验证规则失败,它将产生以下消息:

    当payment type 为信用卡时,credit card number不能为空。
本文为 Wiki 文章,邀您参与纠错、纰漏和优化
讨论数量: 1

代码贴半截,看不懂

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!