amirhs712/rule-builder

Laravel 验证规则构建器

维护者

详细信息

github.com/amirhs712/nope

源代码

问题

安装: 333

依赖: 0

建议者: 0

安全: 0

星标: 3

关注者: 2

分支: 0

开放问题: 0

类型:工具

1.0.0 2020-10-29 11:48 UTC

This package is auto-updated.

Last update: 2024-09-29 06:02:20 UTC


README

Latest Stable Version Total Downloads License

Nope 是一个受 JavaScript 的 Yup 启发的 Laravel 验证规则构建器。

使用 Nope,你可以更流畅地生成规则,我还从 Laravel 官方网站上复制了规则描述并硬编码到 Nope 中,因此你可以轻松访问文档。

一些功能已经扩展到验证规则中,例如,你可以将 Carbon 实例传递给日期验证规则,如 after

安装

使用以下命令通过 composer 安装此包

   composer require amirhs712/rule-builder

用法

我建议使用 nope() 全局辅助函数以实现无警告和完整的 ide 检查。你也可以使用 Amirhs712\RuleBuilder\Nope 类。

   $rules = [
        'username' => nope()->required()->string()->max(30)->get(), //[required,string,max:30]

        'password' => Nope::required()->stringOf(30)->confirmed()->get() //[required,string,confirmed,max:30]
];

我们使用 get() 获取数组形式的输出,你也可以使用 toString() 将输出作为管道分隔的字符串返回。

  • toStringget 支持从 -21 的必需状态。
    • 1 => 调用 required 规则
    • 0 => 无操作(默认)
    • -1 => 调用 sometimes 规则
    • -2 => 调用 sometimes & nullable 规则
    $rules = [
        'username' => nope()->stringOf(30)->toString(1), //string|max:30|required

        'password' => nope()->stringOf(30)->toString(-2) //string|max:30|sometimes|nullable
];

使用 Carbon 的日期规则

你可以将碳实例传递给以下日期规则:afterafterOrEqualdateEqualsbeforebeforeOrEqual

    $rules = [
        'date' => nope()->after('today')->get(),

        'another_date' => nope()->afterOrEqual(now()->addMonth())->get(),
];

最小/最大助手

这些方法允许你手动设置最小和/或最大参数。

Rule::activeUrl($max)
    ->alpha($min, $max)
    ->alphaDash($min, $max)
    ->alphaNum($min, $max)
    ->array($min, $max)
    ->file($max)
    ->image($max)
    ->integer($min, $max)
    ->json($max)
    ->numeric($min, $max)
    ->string($min, $max)
    ->url($max);

原始规则

你可以使用 raw(string|array) 添加原始字符串规则或验证对象。

    $rules=[
        'field1' => nope()->raw('string|max:30')->get(),
        'field2' => nope()->raw(['string', 'max:30'])->get(),
        'field3' => nope()->raw(new ValidationObject)->get(),
        'field4' => nope()->raw([new ValidationObject, new AnotherObject])->get(),
        'field5' => nope()->raw('string')->raw('max')->get(),
];
  • 注意:如果你有验证对象,则不能调用 toString 方法。这样做会导致错误。

条件规则

你可以使用 when 方法有条件地添加规则。

nope()->when($conditionIsMet, function(Nope $nope){
    $nope->max(100); 
});

Laravel 约束构建器

innotIndimensionsexistsunique 方法支持它们的相关约束构建器和它们的默认值。

    
$rules = [
    'image1' => nope()->dimensions(['width' => 300, 'height' => 300])->get(),

    'image2' => nope()->dimensions(Rule::dimensions()->width(300)->height(300))->get(),
];

模板

你可以构建和定义自己的规则模板。

即将推出!

未定义的方法

目前对方法调用没有限制(我没有找到这样做的理由),例如,你可以这样做

nope()->myCustomExtendedRule($arg1, $arg2,...)->get(); //Results in: ["my_custom_extended_rule:$arg1, $arg2,..."]

替代方案

你可以查看这个包作为替代方案,我已经实现了这个包的一些想法并将它们合并到了自己的解决方案中。

反馈

如果你有任何建议,请随时打开问题或拉取请求。