我有一系列的开放时间和关闭时间。
输入如下:
<input type="text" name="time[1][open]">
<input type="text" name="time[1][close]">
<input type="text" name="time[x][open]">
<input type="text" name="time[x][close]">
这是来自dd($request->all())
的转储
array:2 [
"days" => array:2 [
0 => "1" // Mon
1 => "2" // Tue
]
"time" => array:2 [
1 => array:2 [
"open" => "09:00"
"close" => "11:30"
]
2 => array:2 [
"open" => "16:00"
"close" => "21:00"
]
]
]
使用Laravel请求验证--如何在打开时间和关闭时间之间循环验证,以确保不重叠mysql数据库中的现有记录?例如,我们可能在数据库中有Open:14:00 -关闭:19:00,但是用户有"open" => "16:00"
和"close" => "21:00"
的请求,所以验证不应该通过。
更新:
示例结果在times
表中,一天可以有多个打开/关闭时间。
id | day | open_time | close_time
-----------------------------------------------
1 | 1 | 13:30:00 | 15:00:00
2 | 2 | 16:30:00 | 20:00:00
3 | 3 | 09:30:00 | 14:30:00
4 | 3 | 18:00:00 | 22:00:00
-----------------------------------------------
您可以看到来自times.id=2
(16:30:00 - 20:00:00)和用户请求"open" => "16:00"
和"close" => "21:00"
的重叠。验证不应通过。
发布于 2016-11-17 13:54:09
这不是一个完整的答案,但它可能对OP有帮助。我仍然不明白天/时间等之间的关系,这是没有逻辑的样板,需要实现。
首先创建新的提供者(用于自定义验证规则)
$ php artisan make:provider ValidatorServiceProvider
并在config/app.php中注册
...
App\Providers\RouteServiceProvider::class,
App\Providers\ValidatorServiceProvider::class,
...
为新的验证规则创建新的文件夹/文件:
$ mkdir ./app/Validators
$ touch ./app/Validators/OverlappingTimeValidator.php
并在新的Validator规则中添加一些代码(由于我不完全理解问题,也许我缺乏理解它的语言技能,所以无法理解逻辑)。
<?php
namespace App\Validators;
class OverlappingTimeValidator
{
public function validate($attribute, $value, $parameters, $validator)
{
//make sure you have valid time format (for each time[])
//make sure open < close for each pair
//compare each set of open-close times with each other
//connect to database and get all required data from $parameters[0] table
//to connect to database and get data use \DB::table($parameters[0])->get(); follow this https://laravel.com/docs/5.3/queries#retrieving-results
//array_get($validator->getData(), $parameters[1], null); // gives you days user picked or null
dd($attribute, $value, $parameters, $validator);
return false; //in case validation fails
return true; //in case validation passes
}
}
运行$ composer dump-autoload
,以便自动加载新文件。
ValidatorServiceProvider.php中的注册验证规则
public function boot()
{
Validator::extend('overlapping_time', 'App\Validators\OverlappingTimeValidator@validate');
}
最后,请求中的规则应该如下所示:
public function rules()
{
return [
'time' => 'overlapping_time:table_name,days'
];
}
您可以使用'time.*'
和验证将分别运行每次您可能不想!因此,使用'time'
并对整个数组进行验证。
正如我所理解的,天数是验证时间中的相关属性,因此我添加了它作为参数,但是您可以更改它。请查看
dd()
在OverlappingTimeValidator@validate
输出中的内容。
为了添加错误消息,打开./resources/lang/en/validation.php
并添加(接近底部,实际上并不重要):
'overlapping_time' => 'The :attribute...',
发布于 2016-11-16 17:13:49
你可以试着
'time.*.open' => 'required',
'time.*.close' => 'after:time.*.open',
请参考此链接
https://stackoverflow.com/questions/40638058
复制相似问题