[英]Laravel 5 validate string with multiple dates comma separated
如何使用laravel验证来验证此字符串? 我想检查逗号之间的日期是否为日期。
2017-11-11,2017-12-11-2017,2017-13-11
回复您的评论。 是的,laravel可以通过创建这样的请求类来做到这一点。
<?php namespace App\Laravel\Requests\Backoffice;
use Session,Auth, Input;
use App\Laravel\Requests\RequestManager;
class DateRequest extends RequestManager{
public function rules(){
$rules = [
//validate if the value is a date and check the date_format must be in "Y-d-m" form
'date' => 'date|date_format:"Y-d-m"',
];
return $rules;
}
public function messages(){
return [
'date' => "Invalid date.",
'date_format' => "Invalid date format.",
];
}
}
您可以使用explode()数组函数,它拆分一个字符串并将其转换为数组。
$date_string = '2017-11-11,2017-12-11-2017,2017-13-11';
//Split the $date_string
$dates = explode(',',$date_string);
//get the values of the $dates variable
foreach($dates as $date){
//Check if the $date values are valid or not
if(Carbon::createFromFormat('DATE FORMAT',$date) !== false){
//valid date format
}else{
//invalid date format
}
}
您可以通过更优雅地使用“规则对象”来做到这一点,下次您可以重复使用此验证/规则。
运行php artisan make:rule Stringdate
app/Rules/Stringdate.php
文件将生成。
这样的变更通行证方法
public function passes($attribute, $value)
{
if(!$value){
return false;
}
$dates = explode(',',$value);
foreach ($dates as $date){
if(preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$date) < 1){
return false;
}
}
return true;
}
您可以在控制器中进行验证,例如。
$this->validate(request(),['data' => ['required',new Stringdate()]]);
( data
是您的属性名称 )
在这种情况下,您应该为逗号分隔符日期字符串创建一个自定义验证器,以便仍然可以使用Request类。
public function validateSampleCustom($attribute, $value, $parameters){
...do you custom code here
...where value is the passed value from the input field
...parameters are the value after the semi_colon in your request eg : (sample_custom:param1,param2,...,paramn)
}
我可以给你看一些自定义验证器
public function validateOldPassword($attribute, $value, $parameters){
if($parameters){
$user_id = $parameters[0];
$user = User::find($user_id);
return Hash::check($value,$user->password);
}
return FALSE;
}
我只想澄清您的问题,以便我们为您解决问题。 我通过这种方式将其用于我的Request类
'password' => "required|old_password",
然后要包含自定义验证器,则应在AppServiceProvider中调用Validator :: resolver以绑定自定义验证器。
public function boot()
{
// Schema::defaultStringLength(191);
Validator::resolver(function($translator, $data, $rules, $messages)
{
return new CustomValidator($translator, $data, $rules, $messages);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.