how to make an input date field greater than or equal to another date field using validation in laravel

冷暖自知 提交于 2019-11-29 13:53:29
Emil Aspman

I had the same problem. before and after does not work when dates could be the same. Here is my short solution:

NOTE: Laravel 5.3.25 and later have new built in rules: before_or_equal and after_or_equal


// 5.1 or newer
Validator::extend('before_or_equal', function($attribute, $value, $parameters, $validator) {
    return strtotime($validator->getData()[$parameters[0]]) >= strtotime($value);
});

// 5.0 & 4.2
Validator::extend('before_or_equal', function($attribute, $value, $parameters) {
    return strtotime(Input::get($parameters[0])) >= strtotime($value);
});

$rules = array(
    'start'=>'required|date|before_or_equal:stop',
    'stop'=>'required|date',
);

Emil Aspman's answer is correct, but doesn't work for Laravel 5.2. this solution works for Laravel 5.2:

 Validator::extend('before_equal', function($attribute, $value, $parameters, $validator) {
     return strtotime($validator->getData()[$parameters[0]]) >= strtotime($value);
 });

The proper solution would be if you extended the Validator with your own rule. A simple example from the docs:

Validator::extend('foo', function($attribute, $value, $parameters)
{
    return $value == 'foo';
});

Read more here

Yes, you can use after:date or before:date like this:

protected $rules = array(
    'date' => 'after:'.$yourDate
);

or alternatively

protected $rules = array(
    'date' => 'before:'.$yourDate
);

It will do exactly what you described. Also check out the official documentation. You can also specify rules of your own using custom validation rules.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!