How can i validate this string with the laravel validation? I want to check if the dates between the commas is a date.
2017-11-11,2017-12-11-2017,2017-13-11
In reply to your comment. Yes laravel can do that, by creating a request class like this.
<?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.",
];
}
}
You can use explode() array function, It split a string and convert it to array.
$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
}
}
You can do it with using Rule Objects more elegant, next time you can reuse this validation/rule.
Run php artisan make:rule Stringdate
app/Rules/Stringdate.php file will be generated.
change passes method like this
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;
}
The validation you can make in controller, for ex.
$this->validate(request(),['data' => ['required',new Stringdate()]]);
(data is your attribute name)
in that case you should create a custom validator for the comma delimiter date string so can still use the Request class.
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)
}
i can show you some custom validator
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;
}
I just want to clarify your concern so we can help you with your issues. and i use this to my Request class by calling it this way
'password' => "required|old_password",
and then to include the custom validator you should call the Validator::resolver in your AppServiceProvider to bind your custom validator.
public function boot()
{
// Schema::defaultStringLength(191);
Validator::resolver(function($translator, $data, $rules, $messages)
{
return new CustomValidator($translator, $data, $rules, $messages);
});
}