agoalofalife/decompose-validator

用于组织和分解Laravel请求验证的额外包

v1.0.0 2021-04-29 08:18 UTC

This package is auto-updated.

Last update: 2024-09-29 06:14:26 UTC


README

此包可以帮助您在Laravel项目中分解验证

这是什么?

此包为您提供拆分验证字段的机会。每个字段和数据集规则都是一个独立类。这提供了行动的自由,并将验证集中在一个地方。更多了解,请阅读我的文章 medium

安装

composer require agoalofalife/decompose-validator

创建验证值

让我们看看电子邮件验证的例子。应该实现ValidatorValue。描述规则和额外消息。我更喜欢使用默认值在构造函数中将$attribute设置,但您也可以在方法中返回一个字符串。

use agoalofalife\DecomposeValidator\ValidatorValue;

class ConsumerEmail implements ValidatorValue
{
    /**
     * @var string
     */
    private $attribute;
    
    /**
     * @var int
     */
    private $exceptConsumerId;
   
    public function __construct(
        int $consumerId,
        string $attribute = 'email'
    ) {
        $this->exceptConsumerId = $consumerId;
        $this->attribute = $attribute;
    }


    public function getAttribute(): string
    {
        return $this->attribute;
    }

    public function getRules(): array
    {
        return [
            'required',
            'email',
            'unique:users,email,'.$this->exceptConsumerId,
        ];
    }

    public function getMessages(): array
    {
        return [
            "{$this->attribute}.email"         => 'Please field should be email',
            "{$this->attribute}.required"      => 'Please email is required field',
            "{$this->attribute}.unique"        => 'Email has registered already',
            "{$this->attribute}.email_checker" => 'Email does not exist',
        ];
    }
}

在表单请求中使用

注意父类名。您应该扩展它。

use agoalofalife\DecomposeValidator\FormRequestDecompose;

class UpdateUserProfile extends FormRequestDecompose
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules(): array
    {
        return [
            new ConsumerEmail(),
            'name'       => ['required', 'alpha'],
            'age'        => ['integer', 'max:120'],
        ];
    }
}

在简单验证(控制器或外观)中使用

此外,我们还有机会使用简单验证。

/**
 * Store a new blog post.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $validatorValue = new ConsumerEmail(request->auth()->id);
    $validated = $request->validate([
         $validatorObject->getAttribute() => $validatorObject->getRules()
    ]);
    
   //...
}

文章

此外,我还在 medium 上写了这篇文章