joelharkes/laravel-strict-validation

为 Laravel 提供类型安全的验证规则

0.0.1 2023-04-07 19:51 UTC

This package is auto-updated.

Last update: 2024-09-24 15:30:42 UTC


README

Latest Version on Packagist Build status Total Downloads

$data = $request->validate(['input' => [new ValidFloat()]);
is_float($data['input']); // true, even when input was "10" string.

如果您想学习如何自己创建可重用的 PHP 包,请查看我即将推出的 PHP 包开发 视频课程。

安装

您可以通过 composer 安装此包

composer require joelharkes/laravel-strict-validation

用法

$this->validate($request, ['input' => [new ValidFloat()]); // input is always float
$this->validate($request, ['input' => [new ValidCarbon()]); // input is always CARBON

可用规则

namespace Joelharkes\LaravelStrictValidation\Rules;
new ValidDatetime();
new ValidDecimal($digits, $decimals);
new ValidFloat();
new ValidIn(['option1', 'option2']); // make sure value is exactly the same as in the given array.
new ValidInteger();
  • ValidDatetime
  • ValidDate

创建自己的规则

创建自己的类型安全规则很简单。只需扩展 BaseRule 并实现 validate 方法。通过调用 $this->modifyValue($value) 来修改值。

class YourRule extends \Joelharkes\LaravelStrictValidation\Rules\BaseRule
{
    public function validate(string $attribute, mixed $value, \Closure $fail): void
    {
        if (isNotValid($value)) {
            return $fail($attribute, $this->translate('validation.numeric'));
        }
        // when data is valid, but not in right type:
        $this->modifyValue(castToYourType($value));
    }
}