simtabi/enekia

Laravel 框架的一组有用附加验证规则

dev-master 2023-02-26 13:57 UTC

This package is auto-updated.

Last update: 2024-09-26 17:28:10 UTC


README

Enekia: Laravel 验证规则


Intervention 验证

Intervention 验证是 Laravel 自身验证系统的扩展库。该软件包添加了规则来验证数据,如 IBAN、BIC、ISBN、信用卡号等。

Latest Version build Monthly Downloads

安装

您可以使用 Composer 快速轻松地安装此软件包。

通过 Composer 需求此软件包

$ composer require intervention/validation

Laravel 集成

验证库是为与 Laravel 框架(>=7)一起工作而构建的。它包含一个服务提供程序,该程序将被自动发现并注册验证规则到您的安装中。该软件包提供了 30 个附加验证规则,包括错误信息,可以像 Laravel 自身验证规则一样使用。

use Illuminate\Support\Facades\Validator;
use Simtabi\Enekia\Laravel\Traits\Rules\CreditCard;
use Simtabi\Enekia\Laravel\Traits\Rules\HexColor;
use Simtabi\Enekia\Laravel\Traits\Rules\Username;

$validator = Validator::make($request->all(), [
    'color' => new HexColor(3), // pass rule as object
    'number' => ['required', 'creditcard'], // or pass rule as string
    'name' => 'required|min:3|max:20|username', // combining rules works as well
]);

更改错误信息

/resources/lang/<language>/validation.php 中添加相应的键,如下所示

// example
'iban' => 'Please enter IBAN number!',

或者,如文档中所述,直接将自定义消息添加到验证器中。

独立使用

也可以在没有 Laravel 框架的情况下使用此库。您将没有 Laravel 门面可用,所以请确保在您的调用中使用 Simtabi\Enekia\Validator

use Simtabi\Enekia\Validator;
use Simtabi\Enekia\Laravel\Traits\Rules\CreditCard;
use Simtabi\Enekia\Laravel\Exceptions\EnekiaException;

// use static factory method to create laravel validator
$validator = Validator::make($request->all(), [
    'ccnumber' => new CreditCard(),
    'iban' => ['required', 'iban'],
    'color' => 'required|hexcolor:3',
]);

// validate single values by calling static methods
$result = Validator::isHexcolor('foobar'); // false
$result = Validator::isHexcolor('#ccc'); // true
$result = Validator::isBic('foo'); // false

// assert single values
try {
    Validator::assertHexcolor('foobar');
} catch (EnekiaException $e) {
    $message = $e->getMessage();
}

可用规则

此软件包提供了以下验证规则。

Base64 编码的字符串

正在验证的字段必须被 Base64 编码

public Simtabi\Enekia\Laravel\Traits\Rules\Base64::__construct()

商业识别代码 (BIC)

检查有效的 商业识别代码 (BIC)。

public Simtabi\Enekia\Laravel\Traits\Rules\Bic::__construct()

驼峰式字符串

正在验证的字段必须格式化为 驼峰式

public Simtabi\Enekia\Laravel\Traits\Rules\Camelcase::__construct()

无类域间路由 (CIDR)

检查值是否为 无类域间路由 表示法 (CIDR)。

public Simtabi\Enekia\Laravel\Traits\Rules\Cidr::__construct()

信用卡号

正在验证的字段必须是有效的 信用卡号

public Simtabi\Enekia\Laravel\Traits\Rules\Creditcard::__construct()

数据 URI 方案

正在验证的字段必须是有效的 数据 URI

public Simtabi\Enekia\Laravel\Traits\Rules\DataUri::__construct()

域名

正在验证的字段必须是格式良好的 域名

public Simtabi\Enekia\Laravel\Traits\Rules\Domainname::__construct()

欧洲文章号 (EAN)

检查有效的 欧洲文章号

public Simtabi\Enekia\Laravel\Traits\Rules\Ean::__construct(?int $length = null)

参数

长度

可选整数长度(8 或 13),仅检查 EAN-8 或 EAN-13。

全球贸易项目编号 (GTIN)

检查有效的 全球贸易项目编号

public Simtabi\Enekia\Laravel\Traits\Rules\Gtin::__construct(?int $length = null)

参数

长度

可选整数长度,仅检查某些类型(GTIN-8、GTIN-12、GTIN-13 或 GTIN-14)。

十六进制颜色代码

正在验证的字段必须是有效的 十六进制颜色代码

public Simtabi\Enekia\Laravel\Traits\Rules\HexColor::__construct(?int $length = null)

参数

长度

可选长度作为整数,仅检查简写(3 个字符)或完整十六进制(6 个字符)形式。

无 HTML 文本

正在验证的字段必须不包含任何 html 代码。

public Simtabi\Enekia\Laravel\Traits\Rules\HtmlClean::__construct()

国际银行账号 (IBAN)

检查有效的国际银行账户号码 (IBAN)。

public Simtabi\Enekia\Laravel\Traits\Rules\Iban::__construct()

国际移动设备身份码 (IMEI)

正在验证的字段必须是国际移动设备身份码 (IMEI)。

public Simtabi\Enekia\Laravel\Traits\Rules\Imei::__construct()

国际标准书号 (ISBN)

正在验证的字段必须是一个有效的国际标准书号 (ISBN)。

public Simtabi\Enekia\Laravel\Traits\Rules\Isbn::__construct(?int $length = null)

参数

长度

可选长度参数作为整数,仅用于检查ISBN-10或ISBN-13。

国际证券识别码 (ISIN)

检查有效的国际证券识别码 (ISIN)。

public Simtabi\Enekia\Laravel\Traits\Rules\Isin::__construct()

国际标准连续出版物编号 (ISSN)

检查有效的国际标准连续出版物编号 (ISSN)。

public Simtabi\Enekia\Laravel\Traits\Rules\Issn::__construct()

JSON Web Token (JWT)

给定的值必须是格式为JSON Web Token

public Simtabi\Enekia\Laravel\Traits\Rules\Jwt::__construct()

烤肉串式字符串

给定的值必须格式化为烤肉串式

public Simtabi\Enekia\Laravel\Traits\Rules\Kebabcase::__construct()

小写字符串

给定的值必须是全部小写字母。

public Simtabi\Enekia\Laravel\Traits\Rules\Lowercase::__construct()

Luhn算法

给定的值必须通过其包含的Luhn算法校验位验证。

public Simtabi\Enekia\Laravel\Traits\Rules\Luhn::__construct()

媒体(MIME)类型

检查有效的Mime类型(媒体类型)。

public Simtabi\Enekia\Laravel\Traits\Rules\MimeType::__construct()

邮政编码

正在验证的字段必须是给定国家的邮政编码

public Simtabi\Enekia\Laravel\Traits\Rules\Postalcode::__construct(string $countrycode)

参数

countrycode

ISO-639-1格式的国家代码。

邮政编码(静态实例化)

public static Simtabi\Enekia\Laravel\Traits\Rules\Postalcode::countrycode(string $countrycode): Postalcode

参数

countrycode

ISO-639-1格式的国家代码。

邮政编码(静态实例化与回调)

public static Simtabi\Enekia\Laravel\Traits\Rules\Postalcode::resolve(callable $callback): Postalcode

参数

callback

回调以从其他来源解析ISO-639-1国家代码。

邮政编码(静态实例化与引用)

public static Simtabi\Enekia\Laravel\Traits\Rules\Postalcode::reference(string $reference): Postalcode

参数

reference

参考键从验证器中的其他数据获取ISO-639-1国家代码。

语义版本号

正在验证的字段必须是使用语义版本控制的有效版本号。

public Simtabi\Enekia\Laravel\Traits\Rules\SemVer::__construct()

SEO友好型简短文本(Slug)

正在验证的字段必须是一个用户和SEO友好型简短文本

public Simtabi\Enekia\Laravel\Traits\Rules\Slug::__construct()

蛇形字符串

正在验证的字段必须格式化为蛇形文本。

public Simtabi\Enekia\Laravel\Traits\Rules\Snakecase::__construct()

标题字符串

正在验证的字段必须格式化为标题

public Simtabi\Enekia\Laravel\Traits\Rules\Titlecase::__construct()

通用唯一排序标识符 (ULID)

正在验证的字段必须是一个有效的通用唯一排序标识符

public Simtabi\Enekia\Laravel\Traits\Rules\Ulid::__construct()

大写字符串

正在验证的字段必须全部为大写。

public Simtabi\Enekia\Laravel\Traits\Rules\Uppercase::__construct()

用户名

正在验证的字段必须是一个有效的用户名。由字母数字字符、下划线、减号组成,以字母字符开头。不允许有多个下划线和减号字符。下划线和减号字符不允许在开头或结尾。

public Simtabi\Enekia\Laravel\Traits\Rules\Username::__construct()

AuthorizedOnModelAction

确定用户是否有权在给定模型的实例上执行能力。模型的id是正在验证的字段

考虑以下策略

class ModelPolicy
{
    use HandlesAuthorization;

    public function edit(User $user, Model $model): bool
    {
        return $model->user->id === $user->id;
    }
}

如果登录用户的id与请求中model_id键对应的TestModel上的user_id匹配,则此验证规则将通过。

// in a `FormRequest`

use Simtabi\Enekia\Laravel\Traits\Rules\AuthorizedOnModelAction;

public function rules()
{
    return [
        'model_id' => [new AuthorizedOnModelAction('edit', TestModel::class)],
    ];
}

可选地,您可以将身份验证守卫作为第三个参数提供。

new AuthorizedOnModelAction('edit', TestModel::class, 'guard-name')

模型解析

如果您在自己的模型中实现了getRouteKeyName方法,则将使用它来解决模型实例。更多信息请参见自定义默认键名

CountryCode

确定验证的字段是否是有效的2字母ISO3166国家代码(有效的国家代码示例:GBDKNL)。

注意,此规则需要安装包league/iso3166composer require league/iso3166

// in a `FormRequest`

use Simtabi\Enekia\Laravel\Traits\Rules\Country;

public function rules()
{
    return [
        'country_code' => ['required', new Country()],
    ];
}

如果您想验证可为空的国家代码字段,可以在CountryCode规则上调用nullable()方法。这样null0也是通过值。

// in a `FormRequest`

use Simtabi\Enekia\Laravel\Traits\Rules\Country;

public function rules()
{
    return [
        'country_code' => [(new Country())->nullable()],
    ];
}

Currency

确定验证的字段是否是有效的3字母ISO4217货币代码(有效的货币示例:EURUSDCAD)。

注意,此规则需要安装包league/iso3166composer require league/iso3166

// in a `FormRequest`

use Simtabi\Enekia\Laravel\Traits\Rules\Currency;

public function rules()
{
    return [
        'currency' => ['required', new Currency()], // Must be present and a valid currency
    ];
}

如果您想验证可为空的货币字段,只需像在Laravel 文档中描述的那样不要将其设置为必填即可。

... 当一个正在验证的属性不存在或包含空字符串时,不会运行正常验证规则,包括自定义规则。

// in a `FormRequest`

use Simtabi\Enekia\Laravel\Traits\Rules\Currency;

public function rules()
{
    return [
        'currency' => [new Currency()], // This will pass for any valid currency, an empty value or null
    ];
}

ModelsExist

确定输入数组中的所有值是否作为给定模型类的属性存在。

默认情况下,该规则假定您希望使用id属性进行验证。在下面的示例中,如果所有model_ids都存在于Model中,则验证将通过。

// in a `FormRequest`

use Simtabi\Enekia\Laravel\Traits\Rules\ModelIdsExist;

public function rules()
{
    return [
        'model_ids' => ['array', new ModelIdsExist(Model::class)],
    ];
}

您也可以传递一个属性名称作为第二个参数。在下面的示例中,如果请求中的user_emails中每个电子邮件都有对应的用户,则验证将通过。

// in a `FormRequest`

use Simtabi\Enekia\Laravel\Traits\Rules\ModelIdsExist;

public function rules()
{
    return [
        'user_emails' => ['array', new ModelIdsExist(User::class, 'emails')],
    ];
}

Delimited

此规则可以验证包含分隔值的字符串。构造函数接受一个用于验证所有单独值的规则。

以下是一个示例,我们将验证包含逗号分隔的电子邮件地址的字符串。

// in a `FormRequest`

use Simtabi\Enekia\Laravel\Traits\Rules\Delimited;

public function rules()
{
    return [
        'emails' => [new Delimited('email')],
    ];
}

以下是一些通过此规则的示例输入

  • 'sebastian@example.com, alex@example.com'
  • ''
  • 'sebastian@example.com'
  • 'sebastian@example.com, alex@example.com, brent@example.com'
  • ' sebastian@example.com , alex@example.com , brent@example.com '

以下输入将不会通过

  • '@example.com'
  • 'nocomma@example.com nocommatoo@example.com'
  • 'valid@example.com, invalid@'

设置最小值

您可以设置必须存在的项目的最小数量

(new Delimited('email'))->min(2)
  • 'sebastian@example.com, alex@example.com' // 通过
  • 'sebastian@example.com' // 失败

设置最大值

(new Delimited('email'))->max(2)
  • 'sebastian@example.com' // 通过
  • 'sebastian@example.com, alex@example.com, brent@example.com' // 失败

允许重复项

默认情况下,如果找到重复项,则规则将失败。

  • 'sebastian@example.com, sebastian@example.com' // 失败

您可以通过这种方式允许重复项

(new Delimited('numeric'))->allowDuplicates()

现在这将通过: 1,1,2,2,3,3

自定义分隔符

(new Delimited('email'))->separatedBy(';')
  • 'sebastian@example.com; alex@example.com; brent@example.com' // 通过
  • 'sebastian@example.com, alex@example.com, brent@example.com' // 失败

跳过项目修剪

(new Delimited('email'))->doNotTrimItems()
  • 'sebastian@example.com,freek@example.com' // 通过
  • 'sebastian@example.com, freek@example.com' // 失败
  • 'sebastian@example.com , freek@example.com' // 失败

复合规则

验证器的构造函数接受一个验证规则字符串、一个验证实例或一个数组。

new Delimited('email|max:20')
  • 'short@example.com' // 通过
  • 'invalid' // 失败
  • 'loooooooonnnggg@example.com' // 失败

传递自定义错误信息

验证器的构造函数接受一个自定义错误信息数组作为第二个参数。

// in a `FormRequest`

use Simtabi\Enekia\Laravel\Traits\Rules\Delimited;

public function rules()
{
    return [
        'emails' => [new Delimited('email', $this->messages())],
    ];
}

public function messages()
{
    return [
        'emails.email' => 'Not all the given e-mails are valid.',
    ];
}

Laravel 模型存在规则

Latest Version on Packagist Build Status Total Downloads

Laravel 验证规则,用于检查模型是否存在。

如果你想使用标准 Laravel 的 Rule::exists('table', 'column') 验证规则不够强大,或者需要添加连接(join)或使用 Eloquent.Builder 的高级功能(如 whereHas),这个规则可能适合你。

安装

你可以通过 composer 安装此包。

composer require mvanduijker/laravel-model-exists-rule

使用方法

简单

<?php

use Duijker\LaravelModelExistsRule\ModelExists;
use Illuminate\Foundation\Http\FormRequest;

class ExampleUserRequest extends FormRequest
{
    public function rules()
    {
        return [
            'user_id' => [
                'required',
                new ModelExists(\App\Models\User::class, 'id'),        
            ],
        ];
    }
}

高级

<?php

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class ExampleUserRequest extends FormRequest
{
    public function rules()
    {
        return [
            'user_id' => [
                'required',
                Rule::modelExists(\App\Models\User::class, 'id', function (Builder $query) {
                    $query->whereHas('role', function (Builder $query) {
                        $query->whereIn('name', ['super-admin', 'admin']);
                    });                    
                }),        
            ],
        ];
    }
}

扩展RFC3339

PHP 不能正确验证 RFC3339: laravel/framework#35387

  • 例如 2020-12-21T23:59:59+00:002020-12-21T23:59:59Z 返回 false,但实际上它是 true

规则 统一日期格式为:YYYY-MM-DDThh:mm:ss.mmm+nn:nn

使用方法

<?php
namespace App\Api\Controllers;
use App\Http\Controllers\Controller;

use Simtabi\Enekia\Laravel\Traits\Rules\ExtendedRFC3339;

class MyController extends Controller
{
    public function index()
    {
        $myData = ['starttime' => '2022-04-06T12:00:00.123+00:00']
        Validator::make($myData, [
            'starttime'           => [new ExtendedRFC3339()],
        ])->validate();
    }
}

Laravel 粗俗词验证器

<?php
// ...
use Simtabi\Enekia\Laravel\Traits\Rules\Profanity;

class MyController extends Controller
{
    public function store(Request $request)
    {
        $this->validate($request, [
            'username' => ['required', new Profanity()]
        ]);

        // ...
    }
}

验证器将加载你的 config/app.php 文件配置中的默认语言环境,默认为 en如果你的语言环境不受支持,请在此项目的问题跟踪器中提交问题

如果你想使用其他词典,可以将它们作为参数传递给验证器。

<?php
// ...
use Simtabi\Enekia\Laravel\Traits\Rules\Profanity;

class MyController extends Controller
{
    public function store(Request $request)
    {
        $this->validate($request, [
            'username' => ['required', new Profanity('en', 'es')]
        ]);

        // ...
    }
}

你也可以发送一个参数,即文件路径,该文件是一个词典,用于替换默认词典或 添加不受支持的语言环境

<?php
// ...
use Simtabi\Enekia\Laravel\Traits\Rules\Profanity;

class MyController extends Controller
{
    public function store(Request $request)
    {
        $this->validate($request, [
            'username' => ['required', new Profanity('en', 'es', resource_path('lang/fr/dict.php'))]
        ]);

        // ...
    }
}

严格验证

现在你可以严格验证内容中确切的粗俗词。

<?php
// ...
use Simtabi\Enekia\Laravel\Traits\Rules\Profanity;

class MyController extends Controller
{
    public function store(Request $request)
    {
        $this->validate($request, [
            'username' => ['required', (new Profanity())->validateStrictly(true)]
        ]);

        // ...
    }
}

Laravel 密码历史验证

使用方法

此包将观察模型的创建和更新事件(检查配置文件以获取设置)并自动记录密码散列。

在你的表单请求或内联验证中,你只需实例化 Password 类,并将当前用户作为参数传递即可。

<?php
use Simtabi\Enekia\Laravel\Traits\Rules\Password;

$this->validate($request, [
            'password' => [
                'required', (new Password())->checkIfUsedBefore($request->user())
            ]
        ]);

清理旧记录 - (可选)

因为我们将在你的数据库中存储散列后的密码,所以随着用户数量的增加,你的数据库可能会变长。

将 PasswordHistoryTrait 添加到你的用户模型中

<?php
use Simtabi\Enekia\Laravel\Traits\HasPasswordHistory;
use Illuminate\Auth\Authenticatable;

class User extends Authenticatable
{
    use Notifiable, HasPasswordHistory;

}

然后你可以运行以下 Artisan 命令

php artisan enekia:password-history:clear

许可证

Intervention Validation 在 MIT 许可证 下授权。

鸣谢

鸣谢