Laravel-如何用相对格式验证日期?



PHP定义了相对格式,Laravel没有可用的验证规则。例如:

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'created-at-from' => 'relative_format',
'created-at-until' => 'nullable|relative_format|gte:created-at-from'
];
}

我们如何验证这些格式?

更新

我现在使用什么:

创建规则类。

php artisan make:rule RelativeFormat

把逻辑。

/**
* Determine if the validation rule passes.
*
* @param  string  $attribute
* @param  mixed  $value
* @return bool
*/
public function passes($attribute, $value)
{
return (bool) strtotime($value);
}

并验证:

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'created-at-from' => [new RelativeFormat],
'created-at-until' => ['nullable', new RelativeFormat]
];
}

您可以创建自己的验证规则:

Validator::extend('relative_format', function($attribute, $value, $parameters)
{
return (bool) strtotime($value);
});

并将其添加到应用服务提供商。

最新更新