Laravel 5以逗号分隔多个日期验证字符串

时间:2017-11-30 13:37:49

标签: php laravel-5

如何使用laravel验证验证此字符串?我想检查逗号之间的日期是否为日期。

2017-11-11,2017-12-11-2017,2017-13-11

4 个答案:

答案 0 :(得分:1)

回复你的评论。是的laravel可以通过创建这样的请求类来做到这一点。

<?php namespace App\Laravel\Requests\Backoffice;

use Session,Auth, Input;
use App\Laravel\Requests\RequestManager;

class DateRequest extends RequestManager{

    public function rules(){

        $rules = [
            //validate if the value is a date and check the date_format must be in "Y-d-m" form
            'date' => 'date|date_format:"Y-d-m"',
        ];

        return $rules;
    }

    public function messages(){
        return [
            'date' => "Invalid date.",
            'date_format' => "Invalid date format.",
        ];
    }
}

答案 1 :(得分:0)

你可以使用explode()数组函数,它拆分一个字符串并将其转换为数组。

    $date_string = '2017-11-11,2017-12-11-2017,2017-13-11';

    //Split the $date_string
    $dates = explode(',',$date_string);

    //get the values of the $dates variable
    foreach($dates as $date){

      //Check if the $date values are valid or not
      if(Carbon::createFromFormat('DATE FORMAT',$date) !== false){
         //valid date format
      }else{
         //invalid date format
      }

    }

答案 2 :(得分:0)

您可以使用更优雅的规则对象来执行此操作,下次您可以重复使用此验证/规则。

运行php artisan make:rule Stringdate

app/Rules/Stringdate.php文件将被生成。

像这样改变传递方法

public function passes($attribute, $value)
    {
        if(!$value){
            return false;
        }
        $dates = explode(',',$value);

        foreach ($dates as $date){

            if(preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$date) < 1){
                return false;
            }
        }

        return true;
    }

您可以在控制器中进行验证,例如。

$this->validate(request(),['data' => ['required',new Stringdate()]]);

data是您的属性名称

答案 3 :(得分:0)

在这种情况下,您应该为逗号分隔符日期字符串创建自定义验证器,因此仍然可以使用Request类。

public function validateSampleCustom($attribute, $value, $parameters){

        ...do you custom code here
        ...where value is the passed value from the input field
        ...parameters are the value after the semi_colon in your request eg : (sample_custom:param1,param2,...,paramn)

    }

我可以向您展示一些自定义验证器

public function validateOldPassword($attribute, $value, $parameters){

        if($parameters){
            $user_id = $parameters[0];
            $user = User::find($user_id);
            return Hash::check($value,$user->password);
        }

        return FALSE;
    }

我只想澄清您的疑虑,以便我们可以帮助您解决问题。我通过这样的方式将它用于我的Request类

'password' => "required|old_password",

然后要包含自定义验证程序,您应该在AppServiceProvider中调用Validator :: resolver来绑定自定义验证程序。

public function boot()
    {
        // Schema::defaultStringLength(191);

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