a-h-abid/laravalerors

带有验证规则名称的 Laravel API 验证错误响应。

0.1 2023-10-15 18:45 UTC

This package is auto-updated.

Last update: 2024-09-15 20:51:07 UTC


README

提供规则名称和参数到 Laravel REST API 验证错误。

嗯...这是啥?

在 API 验证错误期间,您不会得到像这样的 422 验证错误响应

{
    "message": "The given data was invalid.",
    "errors": {
        "name": [
            "The name field is required."
        ],
        "age": [
            "The age field must be at least 18."
        ]
    }
}

您将得到以下响应

{
    "message": "The given data was invalid.",
    "errors": {
        "name" : [
            {
                "rule": "required",
                "options": [],
                "message": "The name field is required."
            }
        ],
        "age" : [
            {
                "rule": "min",
                "options": ["18"],
                "message": "The age field must be at least 18"
            }
        ]
    }
}

对于每个错误,您都会得到规则名称及其参数。

好吧...我为什么需要?

如果您的消费者/客户端想要为每个规则使用与 Laravel 提供的不同的消息,他们现在可以使用规则名称和参数来为其客户提供自己的消息。

需求

  • Laravel 10.0+

安装(composer)

composer require a-h-abid/laravalerors

配置

将以下代码添加到 app/Exceptions/Handler.php 文件中。

use Illuminate\Validation\ValidationException;

// ...

    /**
     * @inheritDoc
     */
    protected function invalidJson($request, ValidationException $exception)
    {
        return response()->json([
            'message' => $exception->getMessage(),
            'errors' => $exception->errorsForApi(),
        ], $exception->status);
    }

用法

现在只需创建一个带有验证规则的 API 端点,使用您最喜欢的 REST API 客户端(Postman、Insomnia 等)对其进行测试,并查看结果。

工作原理

对于每个规则错误,返回匹配的规则名称及其参数。我们还返回规则错误消息,以便消费者/客户端可以更好地理解错误。

  • 对于 Laravel 内置验证,规则名称以小写格式返回,除非它是基于类的规则。
  • 对于基于类的验证,我们将类的短名称转换为下划线分隔的小写。然而,
    • 如果有 public const RULE_NAME (字符串),则使用此规则名称。
    • 如果有 public const RULE_PARAMS (字符串数组),则使用此规则参数。
  • 对于基于闭包的验证。您将始终得到规则名称 "closure-validation-rule",因为目前无法自定义。

自定义规则类示例

<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class InCategory implements ValidationRule
{
    /** @var string */
    public const RULE_NAME = 'in-category';

    /** @var array<int,string> */
    public const RULE_PARAMS = ['a', 'b', 'c'];

    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (!in_array($value, static::RULE_PARAMS)) {
            $fail('The :attribute you provided is not within the acceptable options.');
        }
    }
}

许可证

许可证