【问题标题】:Laravel How to Make Custom Validator?Laravel 如何制作自定义验证器?
【发布时间】:2016-07-15 21:05:54
【问题描述】:

我需要制作自己的验证器来扩展Illuminate\Validation\Validator

我在此处阅读了答案中给出的示例:Custom validation in Laravel 4

但问题是它没有清楚地显示如何使用自定义验证器。它不会显式调用自定义验证器。你能给我一个如何调用自定义验证器的例子吗?

【问题讨论】:

标签: php laravel validation


【解决方案1】:

在 Laravel 5.5 之后,您可以创建自己的自定义验证规则对象。

要创建新规则,只需运行 artisan 命令:

php artisan make:rule GreaterThanTen

laravel 会将新的规则类放在app/Rules 目录中

自定义对象验证规则的示例可能类似于:

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class GreaterThanTen implements Rule
{
    // Should return true or false depending on whether the attribute value is valid or not.
    public function passes($attribute, $value)
    {
        return $value > 10;
    }

    // This method should return the validation error message that should be used when validation fails
    public function message()
    {
        return 'The :attribute must be greater than 10.';
    }
}

定义了自定义规则后,您可以像这样在控制器验证中使用它:

public function store(Request $request)
{
    $request->validate([
        'age' => ['required', new GreaterThanTen],
    ]);
}

这种方式比在AppServiceProvider 类上创建Closures 的旧方式要好得多

【讨论】:

  • 我知道这是一个相当老的答案,但我是 Laravel 的新手,可以澄清一下:我在 CV 中看到的大多数示例都显示了 Controller 操作中的基本用法。如果我使用表单请求,上面的示例是否可以在 rules() 函数中作为 return ['age' => 'greaterthanten']; 工作?
  • @cautionbug,是的,您可以在表单请求类中使用 CV,您只需导入新的自定义验证规则类:use App\Rules\GreaterThanTen;
  • ['required', new GreaterThanTen] 不起作用,请改用 [$request, new GreaterThanTen]
【解决方案2】:

我不知道这是否是您想要的,但要设置自定义规则,您必须首先扩展自定义规则。

Validator::extend('custom_rule_name',function($attribute, $value, $parameters){
     //code that would validate
     //attribute its the field under validation
     //values its the value of the field
     //parameters its the value that it will validate againts 
});

然后将规则添加到您的验证规则中

$rules = array(
     'field_1'  => 'custom_rule_name:parameter'
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 2012-11-27
    • 2021-11-14
    • 1970-01-01
    相关资源
    最近更新 更多