繁体   English   中英

Laravel如何制作自定义验证器?

[英]Laravel How to Make Custom Validator?

我需要创建自己的验证器,扩展Illuminate\\Validation\\Validator

我在这里的答案中读到了一个例子: Laravel 4中的自定义验证

但问题是它没有清楚地显示如何使用自定义验证器。 它不会显式调用自定义验证程序。 你能举个例子来说明如何调用自定义验证器吗?

在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的旧方法要好得多

我不知道这是否是你想要的,但是要设置海关规则,首先你需要扩展自定义规则。

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'
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM