Laravel 4:使用验证前后验证开始和结束日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26817045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:23:58  来源:igfitidea点击:

Laravel 4: Validate start and end date with before and after validation

phpvalidationdatelaravel

提问by siddiq

I want to validate two date fields in a form which is from_date and end_date. Need to check from_date is less than end_date.

我想以 from_date 和 end_date 的形式验证两个日期字段。需要检查 from_date 是否小于 end_date。

$rules = array('from_date' => array('sometimes','date_format:"Y-m-d"', 'before:'.Input::get('to_date') ),
                        'to_date' => array('sometimes','date_format:"Y-m-d"', 'after:'.Input::get('from_date') ) );

This is what i tried. But that does not work. If i give the to_date as empty value it will through the error.

这是我试过的。但这不起作用。如果我将 to_date 指定为空值,它将通过错误。

回答by DutGRIFF

Laravel 5:

Laravel 5:

Here is more extensive approach that follows modern principles and is more Laravel-like. This is a little more complex but still easy to follow and the end results is much cleaner.

这是遵循现代原则的更广泛的方法,更像 Laravel。这有点复杂,但仍然很容易遵循,最终结果更清晰。

Let's start by changing a few things. Let's reduce this to the specific problem, use newer array syntax and apply formatting.

让我们从改变一些事情开始。让我们将其简化为特定问题,使用较新的数组语法并应用格式。

$rules = [
  'from_date' => [
    'before:'.Input::get('to_date') // This is what we will learn to do
  ],
  'to_date' => [ 
    'after:'.Input::get('from_date') // Do this one on your own
  ]
];

Now let's create a new Request with php artisan make:request StoreWhateverRequest. This will create the App/HTTP/Request/StoreWhateverRequest.phpfile. Open that and place your rules in the return array of the rules()function.

现在让我们用php artisan make:request StoreWhateverRequest. 这将创建App/HTTP/Request/StoreWhateverRequest.php文件。打开它并将您的规则放在rules()函数的返回数组中。

return [
   'from_date'       => 'date',
   'to_date'         => 'date|after_field:from_date'
 ];

This will not work yet because after_fieldisn't available to use yet. Let's create that. We need a new class that extends validator. You can place it in app/Services. We need something similar to:

这将无法使用,因为尚after_field无法使用。让我们创造那个。我们需要一个扩展验证器的新类。你可以把它放在app/Services. 我们需要类似的东西:

<?php namespace App\Services;

use Illuminate\Validation\Validator;
use Carbon\Carbon;

class AfterFieldValidator extends Validator {
  public function validateAfterField($attribute, $value, $parameters)
  {
    return Carbon::parse($value) > Carbon::parse($this->data[$parameters[0]]);
  }
}

In the above we have: $attributewhich is the name of the field we are checking (to_date), $valueis the value of the field we are checking and $parametersis the parameters we passed to the Validator(from_date) seen in 'to_date' => 'date|afterField:from_date'. We also need the other data fields passed to the Validator, we can get these with $this->data. Then we just have to preform the logic appropriately. You really don't even need Carbon here but be sure to parse the string so we don't do string comparison.

在上面我们有:$attribute这是我们正在检查的字段的名称 (to_date),$value是我们正在检查的字段的值,$parameters是我们传递给 Validator(from_date) 中看到的参数'to_date' => 'date|afterField:from_date'。我们还需要传递给验证器的其他数据字段,我们可以使用$this->data. 然后我们只需要适当地执行逻辑。您在这里甚至不需要 Carbon,但一定要解析字符串,这样我们就不会进行字符串比较。

Now we need to load this into the application. To do this put the below code inside the boot()function in app/Providers/AppServiceProviders.php.

现在我们需要将它加载到应用程序中。要做到这一点把下面的代码里面boot()功能app/Providers/AppServiceProviders.php

Validator::resolver(function($translator, $data, $rules, $messages)
{
  return new afterFieldValidator($translator, $data, $rules, $messages);
});

The final step is easiest. Just inject and instance of StoreWhateverRequestinto our Controller.

最后一步是最简单的。只需注入和实例StoreWhateverRequest到我们的控制器。

...
public function store(StoreWhateverRequest $request)
{
...

All done. I feel this is a pretty SOLID way to solve the problem.

全部完成。我觉得这是解决问题的一种非常可靠的方法。

回答by Kaushik Kumar

Please use the below code in laravel 5.2 and it works fine for validating start and end date.

请在 laravel 5.2 中使用以下代码,它可以很好地验证开始和结束日期。

$this->validate($request, [
            'start_date' => 'required|before:end_date',
            'end_date' => 'required',

        ]); 

回答by Cristian Michel

I know that it is a question about Laravel 4 BUT if you are using Laravel 5.3 now you can use something like:

我知道这是关于 Laravel 4 的问题,但是如果您现在使用 Laravel 5.3,您可以使用以下内容:

$rules = array(

   'date_start' => 'required|date_format:Y-m-d|before_or_equal:date_end',
   'date_end' => 'required|date_format:Y-m-d|after_or_equal:date_start'

       );

    $validator = Validator::make($request->all(), $rules);

回答by cameronoxley

Just came across this and thought I'd share an answer I found: Compare attributes in validation

刚遇到这个,我想我会分享一个我找到的答案:比较验证中的属性

Basically, you'd create a new Validator that extends Illuminate\Validation\Validator and write a custom rule in there:

基本上,您将创建一个扩展 Illuminate\Validation\Validator 的新 Validator 并在其中编写自定义规则:

public function validateEndAfter($attribute, $value, $parameters) {
    $start_date = $this->getValue($parameters[0]); // get the value of the parameter (start_date)
    return (strtotime($value) > strtotime($start_date));
}

then in your validator use the new rule:

然后在您的验证器中使用新规则:

$rules = [
    'start_date'  => 'required',
    'end_date'=> 'required|end_after:start_date',
]

回答by siddiq

Anyhow,

无论如何,

I did as like this. So that even if any date in the form is empty that will auto fill and check the validation

我就是这样做的。这样即使表单中的任何日期为空,也会自动填写并检查验证

$inputs = Input::all();
if(!empty($inputs))
{
    $default_date_arr = array('from_date' => date('Y-m-d', strtotime('-1 days')), 'to_date' => date('Y-m-d'));
    $inputs = $inputs+$default_date_arr;
}
$rules = array('from_date' => array('sometimes','date_format:"Y-m-d"', 'before:'.$to_date) ,
                        'to_date' => array('sometimes','date_format:"Y-m-d"', 'after:'.$from_date ) );
$validator = Validator::make($inputs,$rules);
if($validator->fails())
{ ... }

This may not be the answer for what i asked. But i needed just a way to finish this. May be will helpful for others.

这可能不是我所问的答案。但我只需要一种方法来完成这件事。可能会对其他人有所帮助。