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

Laravel - How to validate dates with relative formats?

PHP 定义了 relative formats and Laravel doesn't seen to have an available validation rule。例如:

/**
 * 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'
    ];
}

我们如何验证这些格式?

更新

我现在用的是:

创建规则class。

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);
});

并将其添加到您的 AppServiceProvider。