如何在控制器 Laravel 中编写自定义验证规则?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41283702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write custom validation rule in controller Laravel?
提问by dsfsddfsdfsf
I have default validation rule in controller Laravel:
我在控制器 Laravel 中有默认验证规则:
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'phone' => 'required|numeric',
'code' => 'required|string|min:3|max:4',
'timezone' => 'required|numeric',
'country' => 'required|integer',
'agreement' => 'accepted'
]);
I tried this, but dont know how to transfer some parameters inside function:
我试过这个,但不知道如何在函数内部传递一些参数:
public function boot()
{
Validator::extend('phone_unique', function($attribute, $value, $parameters) {
return substr($value, 0, 3) == '+44';
});
}
How can I extent this validation by my own rule? For example I need to validate concatination of inputs:
我怎样才能通过我自己的规则来扩展这种验证?例如,我需要验证输入的串联:
$phone = $request->code.' '.$request->phone
After check if $phone
are exists in database
检查$phone
数据库中是否存在后
I want to use this method:
我想用这个方法:
> $validator->sometimes('phone', 'required|alpha_dash|max:25', function
> ($input) {
> if ((Auth::user()->phone == $input->phone)) {
> return false;
>
> } else {
>
> $t = User::where("phone", $input->phone)->get();
> return ($t->count() > 0) ? false : false;
>
> }
> });
It does not work under all conditions (True, False)
inside.
它在(True, False)
内部的所有条件下都不起作用。
I added new validation nickname_unique
:
我添加了新的验证nickname_unique
:
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'code' => 'required|string|min:3|max:4',
'phone' => 'required|phone_unique',
'timezone' => 'required|numeric',
'country' => 'required|integer',
'nickname' => 'required|alpha_dash|max:25',
'agreement' => 'accepted'
], [
'phone_unique' => 'Phone already exists!',
'nickname_unique' => 'Nickname is busy!',
]);
It does not work, even not call validation rule below previos:
它不起作用,甚至不调用之前的验证规则:
Validator::extend('nickname_unique', function ($attribute, $value, $parameters, $validator) {
dd("Here");
});
采纳答案by Saumya Rastogi
You can define your custom validator inside AppServiceProvider
like this:
您可以在其中定义自定义验证器,AppServiceProvider
如下所示:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Validator::extend('phone_unique', function ($attribute, $value, $parameters, $validator) {
$inputs = $validator->getData();
$code = $inputs['code'];
$phone = $inputs['phone'];
$concatenated_number = $code . ' ' . $phone;
$except_id = (!empty($parameters)) ? head($parameters) : null;
$query = User::where('phone', $concatenated_number);
if(!empty($except_id)) {
$query->where('id', '<>', $except);
}
return $query->exists();
});
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
//
}
}
You can get all the inputs passed to the validator, by accessing
$validator
property -getData()
您可以通过访问
$validator
属性来获取传递给验证器的所有输入-getData()
You can just add an extra parameter to your rules array after your custom validation rule (just after the colon
) like this:
您可以在自定义验证规则之后(就在 之后colon
)向规则数组添加一个额外的参数,如下所示:
'phone' => 'required|phone_unique:1',
Pass the
id
to be ignored while checking entries into the db
在
id
将条目检查到数据库时传递要忽略的
The custom validator Closure receives four arguments: the name of the $attribute
being validated, the $value
of the attribute, an array of $parameters
passed to the rule, and the Validator instance.
自定义验证器闭包接收四个参数:$attribute
被验证的名称、$value
属性的名称、$parameters
传递给规则的数组以及 Validator 实例。
Now you can call the validator like this:
现在你可以像这样调用验证器:
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'code' => 'required|string|min:3|max:4',
'phone' => 'required|phone_unique:1',
'timezone' => 'required|numeric',
'country' => 'required|integer',
'agreement' => 'accepted'
], [
'phone_unique' => 'Phone already exists!', // <---- pass a message for your custom validator
]);
See more about Custom Validation Rules.
查看更多关于自定义验证规则。
回答by Matija
I am writing this answer because I believe bunch of people are looking for some good answer for this topic. So I decided to share my code that I am using for booking site, where I want to check that IS NOT arrival_date > departure_date.
我写这个答案是因为我相信很多人都在为这个话题寻找一些好的答案。所以我决定分享我用于预订网站的代码,我想在那里检查是不是到达日期 > 出发日期。
My version of Laravel is 5.3.30
我的 Laravel 版本是 5.3.30
public function postSolitudeStepTwo(Request $request)
{
$rules = [
'arrival_date' => 'required|date',
'departure_date' => 'required|departure_date_check',
'occasional_accompaniment_requested' => 'required|integer',
'accommodation' => 'required|integer',
'are_you_visiting_director' => 'required|integer',
];
if ($request->input('are_you_visiting_director') == 1) {
$rules['time_in_lieu'] = 'required|integer';
}
$messages = [
'departure_date_check' => 'Departure date can\'t be smaller then Arrival date.Please check your dates.'
];
$validation = validator(
$request->toArray(),
$rules,
$messages
);
//If validation fail send back the Input with errors
if($validation->fails()) {
//withInput keep the users info
return redirect()->back()->withInput()->withErrors($validation->messages());
} else {
MySession::setSessionData('arrival_date', $request);
MySession::setSessionData('departure_date', $request);
MySession::setSessionData('occasional_accompaniment_requested', $request);
MySession::setSessionData('accommodation', $request);
MySession::setSessionData('are_you_visiting_director', $request);
MySession::setSessionData('time_in_lieu', $request);
MySession::setSessionData('comment_solitude_step2_1', $request);
//return $request->session()->all();
return redirect("/getSolitudeStepThree");
}
}
My controller is StepControllerand there I have declared a method as you can see called postSolitudeStepTwo. I declare the rules and on departure date notice that for the rule we have required|departure_date_check
. That will be the name of the method in
我的控制器是StepController,我在那里声明了一个方法,你可以看到它叫做 postSolitudeStepTwo。我宣布规则并在出发日期通知我们有规则required|departure_date_check
。这将是方法的名称
app/Providers/AppServiceProvider.php
The code there looks like this:
那里的代码如下所示:
public function boot()
{
Validator::extend('departure_date_check', function ($attribute, $value, $parameters, $validator) {
$inputs = $validator->getData();
$arrivalDate = $inputs['arrival_date'];
$departureDate = $inputs['departure_date'];
$result = true;
if ($arrivalDate > $departureDate) {
$result = false;
}
return $result;
});
}
As the Laravel documentation 5.3 Custom validation ruleswe need to extend the Validator facade, the signature of that method has to be:
由于Laravel 文档 5.3 自定义验证规则我们需要扩展 Validator 门面,该方法的签名必须是:
Validator::extend(name_of_the_function, function ($attribute, $value, $parameters, $validator) {
And I believe the rest is clear.
我相信其余的都很清楚。
Hope it will help somebody.
希望它会帮助某人。
回答by vipinlalrv
$messsages = array(
'email.required'=>'Email is Required',
'phone.required'=>'Phone number is Required',
);
$rules = array(
'email' => 'required',
'phone' => 'required',
);
$validator = Validator::make(Input::all(), $rules,$messsages);
if ($validator->fails()):
$this->throwValidationException($request, $validator);
endif;