How add Custom Validation Rules when using Form Request Validation in Laravel 5(在 Laravel 5 中使用表单请求验证时如何添加自定义验证规则)
问题描述
我正在使用表单请求验证方法来验证 Laravel 5 中的请求.我想使用表单请求验证方法添加我自己的验证规则.下面给出了我的请求类.我想添加带有字段项的自定义验证 numeric_array.
I am using form request validation method for validating request in laravel 5.I would like to add my own validation rule with form request validation method.My request class is given below.I want to add custom validation numeric_array with field items.
protected $rules = [
'shipping_country' => ['max:60'],
'items' => ['array|numericarray']
];
我的自定义函数如下
Validator::extend('numericarray', function($attribute, $value, $parameters) {
foreach ($value as $v) {
if (!is_int($v)) {
return false;
}
}
return true;
});
如何在 laravel5 中使用这种验证方法和表单请求验证?
How can use this validation method with about form request validation in laravel5?
推荐答案
像您一样使用 Validator::extend() 实际上非常好,您只需要将其放入 服务提供者像这样:
Using Validator::extend() like you do is actually perfectly fine you just need to put that in a Service Provider like this:
<?php namespace AppProviders;
use IlluminateSupportServiceProvider;
class ValidatorServiceProvider extends ServiceProvider {
public function boot()
{
$this->app['validator']->extend('numericarray', function ($attribute, $value, $parameters)
{
foreach ($value as $v) {
if (!is_int($v)) {
return false;
}
}
return true;
});
}
public function register()
{
//
}
}
然后通过将其添加到 config/app.php 中的列表来注册提供程序:
Then register the provider by adding it to the list in config/app.php:
'providers' => [
// Other Service Providers
'AppProvidersValidatorServiceProvider',
],
您现在可以在任何地方使用 numericarray 验证规则
You now can use the numericarray validation rule everywhere you want
这篇关于在 Laravel 5 中使用表单请求验证时如何添加自定义验证规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Laravel 5 中使用表单请求验证时如何添加自定义
基础教程推荐
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何替换eregi() 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
